package net.huashitong.supervision.task.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sirdc.modules.core.exceptions.SystemException;
import com.sirdc.modules.core.filter.BaseFilter;
import com.sirdc.modules.core.web.JsonBaseController;
import com.sirdc.modules.core.web.model.JqGrid;
import com.sirdc.modules.core.web.model.Message;
import com.sirdc.modules.sys.entity.SysDept;
import com.sirdc.modules.sys.entity.SysLogin;
import com.sirdc.modules.sys.entity.SysUser;
import com.sirdc.modules.sys.filter.SysUserFilter;
import com.sirdc.modules.sys.service.*;
import com.sirdc.modules.sys.util.SysUserUtils;
import com.sirdc.modules.utils.ObjectUtils;
import com.sirdc.modules.utils.StringUtils;
import net.huashitong.supervision.excel.service.ExcelDataService;
import net.huashitong.supervision.task.dataBean.*;
import net.huashitong.supervision.task.entity.*;
import net.huashitong.supervision.task.filter.*;
import net.huashitong.supervision.task.service.*;
import net.huashitong.supervision.task.service.SpecialService.TaskSpecialService;
import net.huashitong.util.UtilsTools;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

import static net.huashitong.supervision.task.controller.TaskUnitController.splitString;

/**
 * Created with IntelliJ IDEA.
 * User: ling
 * Date: 2019/8/6
 * Time: 19:57
 * To change this template use File | Settings | File Templates.
 * Description:立项单位我的任务
 */
@Controller
@RequestMapping(value = "/taskMain")
public class TaskMainController extends JsonBaseController {
	@Autowired
	private SysDeptService sysDeptService;
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private DeptService deptService;
	@Autowired
	private TaskCategoryService categoryService;
	@Autowired
	private TaskMainService taskMainService;
	@Autowired
	private SysLoginService sysLoginService;
//	@Lazy
	@Autowired
	private TaskSubService taskSubService;
	@Autowired
	private TaskUserService taskUserService;
	@Autowired
	private TaskLogNewService taskLogNewService;
	@Autowired
	private TaskUnitService taskUnitService;
	@Autowired
	private TaskCategoryService taskCategoryService;
	@Autowired
	private TaskBackNewService taskBackNewService;
	@Autowired
	private CopeToService copeToService;
	@Autowired
	private HastenMessageService hastenMessageService;
	@Autowired
	private TaskSpecialService ptService;

	@Autowired
	private DeptTaskRanksService deptTaskRanksService;
	@Lazy
	@Autowired
	private TimeLimitService timeLimitService;
	@Autowired
	private RedisService redisService;
	@Autowired
	private ExcelDataService excelDataService;



	@Override
	protected String getView(String s) {
		return "/modules/task/taskMain/" + s;
	}


	@RequestMapping(value = "/filter", method = RequestMethod.GET)
	public String filter() {
		return getView("filter");
	}

	/**
	 * 返回发布简报页面
	 *
	 * @return
	 */
	@RequestMapping(value = "/smash", method = RequestMethod.GET)
	public String releaseBriefing() {
		return "/modules/task/smash/releaseBriefing";
	}

	/**
	 * 返回立项页面
	 *
	 * @return
	 */
	@RequestMapping(value = "/createTask", method = RequestMethod.GET)
	public String createTask(Model model) {
		//事项类型
		model = updateModel(model);
		return getView("form");
	}

	/**
	 * 事项类型分类
	 *
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/categoryList")
	public List<TaskCategory> taskCategoryList() {
		List<TaskCategory> categoryList = categoryService.query();
		return categoryList;
	}


	public Model updateModel(Model model) {
		List<TaskCategory> categoryList = categoryService.query();
		//所有承办单位的二级 单位
		List<SysDept> sysDeptList = deptService.queryByDeptLevel(3);
		//县领导列表
		List<SysUser> copeToList = new ArrayList<>();
		SysUserFilter userFilter = new SysUserFilter();
		userFilter.setRoleId("01");
		List<SysLogin> list = sysLoginService.queryUserLoginByRoleDept(userFilter);
		//去重
		HashSet<SysUser> sysUsers = new HashSet<>();
		for (SysLogin s : list) {
			SysUser user = sysUserService.getById(s.getSysId());
			copeToList.add(user);
			sysUsers.add(user);
		}

		//当前用户上级领导(审批)
		List<SysUser> leaderList = new ArrayList<>();
		String roleId = SysUserUtils.getRoleId();
		List<SysLogin> loginList = sysLoginService.queryLeaderList(SysUserUtils.getDeptId(), roleId);
		for (SysLogin sysLogin : loginList) {
			SysUser user = sysUserService.getById(sysLogin.getSysId());
			leaderList.add(user);
//            sysUsers.add(user);
		}
		//所有二级 单位
		model.addAttribute("copeToList", copeToList);
		model.addAttribute("leaderList", leaderList);
		model.addAttribute("categoryList", categoryList);
		model.addAttribute("sysDeptList", sysDeptList);
		return model;
	}

	@RequestMapping(value = "/updateTask/{id}", method = RequestMethod.GET)
	public String updateTaskViewForInspection(Model model, @PathVariable String id) {
		TaskMain taskMain = taskMainService.getById(id);
		TaskMainBean taskMainBean = new TaskMainBean();
		BeanUtils.copyProperties(taskMain, taskMainBean);
		String[] files = splitString(taskMain.getFile());
		String[] fileNames = splitString(taskMain.getFileName());
		String[] gJFiles = splitString(taskMain.getgJFile());
		String[] gJfileName = splitString(taskMain.getgJFileName());
		String[] resultFiles = splitString(taskMain.getMainResultFile());
		String[] resultFileNames = splitString(taskMain.getMainResultFileName());
		List<Map<String, Object>> fileMapList = new ArrayList<>();
		if (ObjectUtils.isNotBlank(files)) {
			for (int i = 0; i < files.length; i++) {
				Map<String, Object> map = new HashMap<>();
				map.put("file", files[i]);
				map.put("fileName", fileNames[i]);
				fileMapList.add(map);
			}
			taskMainBean.setFiles(fileMapList);
		}
		if (ObjectUtils.isNotBlank(gJFiles)) {
			List<Map<String, Object>> gjFileMapList = new ArrayList<>();
			for (int i = 0; i < gJFiles.length; i++) {
				Map<String, Object> map = new HashMap<>();
				map.put("file", gJFiles[i]);
				map.put("fileName", gJfileName[i]);
				gjFileMapList.add(map);
			}
			taskMainBean.setgJFile(gjFileMapList);
		}
		if (ObjectUtils.isNotBlank(resultFiles)) {
			List<Map<String, Object>> resultFileMapList = new ArrayList<>();
			for (int i = 0; i < resultFiles.length; i++) {
				Map<String, Object> map = new HashMap<>();
				map.put("file", resultFiles[i]);
				map.put("fileName", resultFileNames[i]);
				resultFileMapList.add(map);
			}
			taskMainBean.setMainResultFile(resultFileMapList);
		}
		model.addAttribute("taskMain", taskMainBean);
		model.addAttribute("type", "1");
		model = updateModel(model);
		return getView("updateTask");
	}


	@RequestMapping(value = "/updateTaskUnit/{id}", method = RequestMethod.GET)
	public String updateTaskViewForUnit(Model model, @PathVariable String id) {
		TaskMain taskMain = taskMainService.getById(id);
		model.addAttribute("taskMain", taskMain);
		model.addAttribute("type", "2");
		model = updateModel(model);
		return getView("updateTask");
	}

	/**
	 * 下载模板
	 *
	 * @param response
	 * @param request
	 * @throws FileNotFoundException
	 */
	@RequestMapping(value = "/downModel", method = RequestMethod.GET)
	public void downModel(HttpServletResponse response, HttpServletRequest request,String type) throws FileNotFoundException, UnsupportedEncodingException {

		InputStream inStream=null;
		String fileName=null;

		if("2".equals(type)){
			// 下载本地文件
			fileName = "督查系统内部立项导表模板.xlsx".toString(); // 文件的默认保存名
			// 读到流中
			inStream = new FileInputStream("c:/dc/督查系统内部立项导表模板.xlsx");// 文件的存放路径
		}else if("3".equals(type)){
			fileName="攻坚任务导入模板.xlsx";
			inStream = new FileInputStream("c:/dc/督查系统_攻坚任务_导入模板.xlsx");// 文件的存放路径

		}else  {

			// 下载本地文件
			fileName = "督查系统导表模板.xlsx".toString(); // 文件的默认保存名
			// 读到流中
			inStream = new FileInputStream("c:/dc/督查系统导表模板.xlsx");// 文件的存放路径
		}
		// 设置输出的格式
		final String agent = request.getHeader("USER-AGENT");
		String filename = fileName;
		if (agent.contains("MSIE")) {
			// IE浏览器
			filename = URLEncoder.encode(filename, "utf-8");
			filename = filename.replace("+", " ");
		} else if (agent.contains("Firefox")) {
			// 火狐浏览器
			filename = new String(fileName.getBytes(), "ISO8859-1");
		} else if (agent.contains("Chrome")) {
			// google浏览器
			filename = URLEncoder.encode(filename, "utf-8");
		} else {
			// 其它浏览器
			filename = URLEncoder.encode(filename, "utf-8");
		}
		response.reset();
		response.setContentType("bin");
		response.addHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
		// 循环取出流中的数据
		byte[] b = new byte[100];
		int len;
		try {
			while ((len = inStream.read(b)) > 0)
				response.getOutputStream().write(b, 0, len);
			inStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 承办单位列表
	 *
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/cbDeptList", method = RequestMethod.POST)
	public List<SysDept> cbDeptList(String deptId) {
		List<SysDept> sysDeptList = deptService.queryByDeptLevel(3);
		if (StringUtils.isNotBlank(deptId)) {
			//去重
			for (Iterator<SysDept> i = sysDeptList.iterator(); i.hasNext(); ) {
				SysDept o = i.next();
				if (o.getSysId().equals(deptId)) {
					i.remove();
				}
			}
			//所有二级 单位
		}
		return sysDeptList;
	}

	/**
	 * 获取县领导列表
	 *
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/leaderList", method = RequestMethod.GET)
	public List<SysUser> leaderList() {
		//县领导列表
		List<SysUser> leaderList = new ArrayList<>();
		SysUserFilter userFilter = new SysUserFilter();
		userFilter.setRoleId("01");
		List<SysLogin> list = sysLoginService.queryUserLoginByRoleDept(userFilter);
		for (SysLogin sysLogin : list) {
			SysUser sysUser = sysUserService.getById(sysLogin.getSysId());
			leaderList.add(sysUser);
		}
		return leaderList;
	}

	/**
	 * 天数转日期
	 * @param day
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/changeTime", method = RequestMethod.POST)
	public String changeTime(String day) {
		String time = taskMainService.changeTime(day);
		return time;
	}

	/**
	 * 保存新建任务 任务立项
	 *
	 * @param filter
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/createTask", method = RequestMethod.POST)
	public String createTask(TaskMainFilter filter) {
		String result = "";
		try {
			result = taskMainService.createTask(filter);
			if(result.contains("保存成功")){
				result = "保存成功";
			}
		} catch (Exception e) {
			e.printStackTrace();
			return e.getMessage();
		}
		return result;
	}

	/**
	 * 更新待立项任务
	 *
	 * @param filter
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/updateTask", method = RequestMethod.POST)
	public Message updateTask(TaskMainFilter filter) {
		String result = "";
		if (StringUtils.isBlank(filter.getSysId())) {
			return coverMessage(UtilsTools.ERROR, "缺少任务id");
		}
		if (StringUtils.isBlank(filter.getCategoryId())) {
			return coverMessage(UtilsTools.ERROR, "请选择事项类型");
		}
		//如果不是周期性任务，需填写任务时限
		if ("1".equals(filter.getTimeType())) {
			if (StringUtils.isBlank(filter.getTimeLimit())) {
				return coverMessage(UtilsTools.ERROR, "请填写任务时限");
			}
		} else if ("2".equals(filter.getTimeType())) {
			if ("0".equals(filter.getPeriod())) {
				if (StringUtils.isBlank(filter.getDay())) {
					return coverMessage(UtilsTools.ERROR, "请填写任务时限");
				}
			} else if ("1".equals(filter.getPeriod())) {
				if (StringUtils.isBlank(filter.getWeek())) {
					return coverMessage(UtilsTools.ERROR, "请填写任务时限");
				}
			} else if ("2".equals(filter.getPeriod())) {
				if (StringUtils.isBlank(filter.getMonth())) {
					return coverMessage(UtilsTools.ERROR, "请填写任务时限");
				}
			} else {
				if (StringUtils.isBlank(filter.getQuarter())) {
					return coverMessage(UtilsTools.ERROR, "请填写任务时限");
				}
			}
		} else {
			if (StringUtils.isBlank(filter.getTimeLimits())) {
				return coverMessage(UtilsTools.ERROR, "请填写任务时限");
			}
		}
		try {
			result = taskMainService.updateTask(filter);
		} catch (Exception e) {
			e.printStackTrace();
			return coverMessage(UtilsTools.ERROR, e.getMessage());
		}
		return coverMessage(UtilsTools.CODE, result);
	}

	/**
	 * 返回主任务详情，审批
	 *
	 * @param taskMainId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/approve/{taskMainId}", method = RequestMethod.GET)
	public TaskMain approve(@PathVariable String taskMainId) {
		TaskMain taskMain = taskMainService.getById(taskMainId);
		return taskMain;
	}

	/**
	 * 审批更改
	 *
	 * @param taskMainId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/approve", method = RequestMethod.POST)
	public Message pass(String taskMainId, String content, String status) {
		String result = taskMainService.updateStatus(taskMainId, content, status);
		if ("200".equals(result)) {
			return coverMessage("200");
		} else {
			return coverMessage("500");
		}
	}


	/**
	 * 待办任务页面
	 *
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/noDoneMain", method = RequestMethod.GET)
	public String noDoneMain(Model model) {
		SysUser user = sysUserService.getById(SysUserUtils.getUserId());
		String roleId = SysUserUtils.getRoleId();
		SysDept dept = sysDeptService.getById(SysUserUtils.getDeptId());
		model.addAttribute("dept", dept);
		model.addAttribute("roleId", roleId);
		model.addAttribute("user", user);
		return getView("noDoneMain");
	}



	/**
	 * 督查组待办任务
	 *
	 * @param taskMainFilter
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/noDoneMain", method = RequestMethod.POST)
	public JqGrid noDoneMain(TaskMainFilter taskMainFilter) {
		if(StringUtils.isNotBlank(taskMainFilter.getSearch())){
			String search = taskMainFilter.getSearch();
			taskMainFilter.setMainName(search);
		}
		//获取当前用户
		String userId = SysUserUtils.getUserId();
		SysUser user = sysUserService.getById(userId);
		SysLogin sysLogin = sysLoginService.getById(userId);
		SysDept dept = sysDeptService.getById(sysLogin.getDeptId());
		String roleId = sysLogin.getRoleId();
		List<TaskMain> list = new ArrayList<>();
		//查看当前用户待审核的任务
		taskMainFilter.setAuditorId(userId);
		taskMainFilter.setStatus("0");
		list = taskMainService.queryFilter(taskMainFilter);
//        taskMainFilter.setOther("DUCHA");
		if ("/01/".equals(dept.getDeptRelation()) && !dept.getDeptName().startsWith("攻坚")) {
			//不是攻坚办
			taskMainFilter.setAuditorId(null);
			taskMainFilter.setStatus("9");
			taskMainFilter.setInspectionId(dept.getSysId());
			taskMainFilter.setCrucialUser("ZAIBAN");
			//查询攻坚系列
			List<TaskMain> listGjian = taskMainService.queryFilter(taskMainFilter);

			list.addAll(listGjian);
		}
		if ("02".equals(roleId)) {
			//单位领导查看单位所有未完成任务
			taskMainFilter.setAuditorId(null);
			taskMainFilter.setInspectionId(sysLogin.getDeptId());
			taskMainFilter.setStatus("3");
			taskMainFilter.setCrucialUser(null);
			List<TaskMain> list1 = taskMainService.queryFilter(taskMainFilter);
			list.addAll(list1);
			Map<String, TaskMain> mainMap = new HashMap<>();
			for (TaskMain taskMain : list) {
				mainMap.put(taskMain.getSysId(), taskMain);
			}
			list = new ArrayList<TaskMain>(mainMap.values());
		} else {
			//如果都不是.那就只能查看自己的任务
			taskMainFilter.setAuditorId(null);
			taskMainFilter.setCrucialUser(null);
			taskMainFilter.setCreateUser(userId);
			taskMainFilter.setStatus("3");
			List<TaskMain> list1 = taskMainService.queryFilter(taskMainFilter);
			list.addAll(list1);
		}
		//这里的顺序，是我自己定义的一个List<String>
		//这里的顺序，是我自己定义的一个List<String>
		String[] regulation = {"3", "0", "2", "4", "1"};
		final List<String> regulationOrder = Arrays.asList(regulation);
//        String[] ordered = {"貂蝉", "诸葛亮", "吕布", "貂蝉", "鲁班", "诸葛亮", "貂蝉", "鲁班", "诸葛亮"};
//        List<String> orderedList = Arrays.asList(ordered);
		Collections.sort(list, new Comparator<TaskMain>() {
			@Override
			public int compare(TaskMain o1, TaskMain o2) {
				int io1 = regulationOrder.indexOf(o1.getStatus());
				int io2 = regulationOrder.indexOf(o2.getStatus());
				return io1 - io2;
			}
		});

		List<TaskMain> taskMainList = new ArrayList<>();
		String deptId = taskMainFilter.getDeptId();
		if (StringUtils.isNotBlank(deptId)) {
			String[] split = deptId.split(",");
			for (String s : split) {
				if (ObjectUtils.isNotBlank(list)) {
					for (TaskMain taskMain : list) {
						List<TaskUnit> taskUnits = taskUnitService.getByMainId(taskMain.getSysId());
						for (TaskUnit taskUnit : taskUnits) {
							if (s.equals(taskUnit.getDeptId())) {
								taskMainList.add(taskMain);
								continue;
							}
						}
					}
				}
			}
			return coverJqGrid(taskMainFilter, taskMainList);
		}else{
			return coverJqGrid(taskMainFilter, list);
		}
	}

	/**
	 * 攻坚任务的待办
	 *
	 * @param
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/noDoneGjMain", method = RequestMethod.POST)
	public JqGrid noDoneGjMain(TaskMainFilter taskMainFilter) {
		if(StringUtils.isNotBlank(taskMainFilter.getSearch())){
			String search = taskMainFilter.getSearch();
			taskMainFilter.setMainName(search);
		}
		String userId = SysUserUtils.getUserId();
		SysLogin sysLogin = sysLoginService.getById(userId);
		SysDept dept = sysDeptService.getById(sysLogin.getDeptId());
		List<TaskMain> list = new ArrayList<>();
		taskMainFilter.setAuditorId(null);
		taskMainFilter.setCrucialState("0");
		if ("/01/".equals(dept.getDeptRelation()) && dept.getDeptName().startsWith("攻坚")) {
			//攻坚办
			if ("02".equals(sysLogin.getRoleId())) {
				// 所有的攻坚 主任务 都是领导看的
				taskMainFilter.setCrucialUser("ALL");
			} else {
				taskMainFilter.setCrucialUser(userId);
			}
			//查询攻坚系列
			//查询攻坚系列
			List<TaskMain> listGjian = taskMainService.queryFilter(taskMainFilter);
			list.addAll(listGjian);
		}
		return coverJqGrid(taskMainFilter, list);
	}

	/**
	 * 抄送给县领导的待办事项
	 *
	 * @param filter
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/unDoneCope", method = RequestMethod.POST)
	public JqGrid unDoneCope(TaskMainFilter filter) {
		String userId = SysUserUtils.getUserId();
		filter.setCopeTo(userId);
		List<TaskMain> copeTaskList = copeToService.queryUnDone(filter);
		return coverJqGrid(filter, copeTaskList);
	}

	/**
	 * 在办任务页面
	 *
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/nowMain", method = RequestMethod.GET)
	public String nowMain(Model model) {
		SysUser user = sysUserService.getById(SysUserUtils.getUserId());
		String roleId = SysUserUtils.getRoleId();
		SysDept dept = sysDeptService.getById(SysUserUtils.getDeptId());
		model.addAttribute("dept", dept);
		model.addAttribute("roleId", roleId);
		model.addAttribute("user", user);
		return getView("nowMain");
	}


	/**
	 * 攻坚任务 （新） 2021-03-31
	 * 合并攻坚任务
	 */
	@ResponseBody
	@RequestMapping(value = "/gongjianTask",method = RequestMethod.POST)
	public JqGrid gongJianTask(TaskMainFilter filter)
	{

		List<TaskMainFilter> gongJianTasks = taskMainService.getGongJianTasks(filter);
		return coverJqGrid(filter,gongJianTasks);
	}


	/**
	 * 攻坚在办
	 *
	 * @param taskMainFilter
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/nowMainGjian", method = RequestMethod.POST)
	public JqGrid nowMainGjian(TaskMainFilter taskMainFilter) {
		if(StringUtils.isNotBlank(taskMainFilter.getSearch())){
			String search = taskMainFilter.getSearch();
			taskMainFilter.setMainName(search);
		}
		String userId = SysUserUtils.getUserId();
		SysLogin sysLogin = sysLoginService.getById(userId);
		SysDept dept = sysDeptService.getById(sysLogin.getDeptId());
		List<TaskMain> list = new ArrayList<>();
		taskMainFilter.setAuditorId(null);
		taskMainFilter.setStatus("4");
		if ("/01/".equals(dept.getDeptRelation()) && dept.getDeptName().startsWith("攻坚")) {
			//攻坚办
			if ("02".equals(sysLogin.getRoleId())) {
				// 所有的攻坚 主任务 都是领导看的
				taskMainFilter.setCrucialUser("ALL");
			} else {
				taskMainFilter.setCrucialUser(userId);
			}
			//查询攻坚系列
			List<TaskMain> listGjian = taskMainService.getUnDoneFilter(taskMainFilter);
			list.addAll(listGjian);
		}
		return coverJqGrid(taskMainFilter, list);
	}

	/**
	 * 督查组zai办任务
	 *
	 * @param taskMainFilter
	 * @retur
	 */
	@ResponseBody
	@RequestMapping(value = "/nowMain", method = RequestMethod.POST)
	public JqGrid nowMain(TaskMainFilter taskMainFilter) {
		if(StringUtils.isNotBlank(taskMainFilter.getSearch())){
			String search = taskMainFilter.getSearch();
			taskMainFilter.setMainName(search);
		}
		//获取当前用户
		String userId = SysUserUtils.getUserId();
		SysUser user = sysUserService.getById(userId);
		SysLogin sysLogin = sysLoginService.getById(userId);
		SysDept dept = sysDeptService.getById(sysLogin.getDeptId());
		String roleId = sysLogin.getRoleId();
		List<TaskMain> list = new ArrayList<>();
		taskMainFilter.setAuditorId(null);
		taskMainFilter.setCrucialUser(null);
		taskMainFilter.setStatus("4");

		if ("02".equals(roleId)) {
			//单位领导查看单位所有未完成任务
			taskMainFilter.setInspectionId(sysLogin.getDeptId());
			list = taskMainService.getUnDoneFilter(taskMainFilter);

		} else {
			//如果都不是.那就只能查看自己的任务
			taskMainFilter.setCreateUser(userId);
			list = taskMainService.getUnDoneFilter(taskMainFilter);

		}
		List<TaskMain> taskMainList = new ArrayList<>();
		if(StringUtils.isNotBlank(taskMainFilter.getDeptId()))
		{
			String deptId = taskMainFilter.getDeptId();
			if (StringUtils.isNotBlank(deptId)) {
				String[] split = deptId.split(",");
				for (String s : split) {
					if (ObjectUtils.isNotBlank(list)) {
						for (TaskMain taskMain : list) {
							List<TaskUnit> taskUnits = taskUnitService.getByMainId(taskMain.getSysId());
							for (TaskUnit taskUnit : taskUnits) {
								if (s.equals(taskUnit.getDeptId())) {
									taskMainList.add(taskMain);
									continue;
								}
							}
						}
					}
				}
				return coverJqGrid(taskMainFilter, taskMainList);
			}else{
				return coverJqGrid(taskMainFilter, list);
			}
		}
		return coverJqGrid(taskMainFilter, list);

	}


	/**
	 * 抄送给县领导的在办办事项
	 *
	 * @param filter
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/nowDoneCope", method = RequestMethod.POST)
	public JqGrid nowDoneCope(TaskMainFilter filter) {
		String userId = SysUserUtils.getUserId();
		filter.setCopeTo(userId);
		List<TaskMain> copeTaskList = copeToService.queryNowDone(filter);
		return coverJqGrid(filter, copeTaskList);
	}

	/**
	 *
	 */
	@RequestMapping(value = "/doneMain", method = RequestMethod.GET)
	public String doneMain(Model model) {
		SysUser user = sysUserService.getById(SysUserUtils.getUserId());
		String roleId = SysUserUtils.getRoleId();
		SysDept dept = sysDeptService.getById(SysUserUtils.getDeptId());
		model.addAttribute("dept", dept);
		model.addAttribute("roleId", roleId);
		model.addAttribute("user", user);
		return getView("doneMain");
	}

	/**
	 * 督查组完成任务
	 *
	 * @param taskMainFilter
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/doneMain", method = RequestMethod.POST)
	public JqGrid doneMain(TaskMainFilter taskMainFilter) {
		if(StringUtils.isNotBlank(taskMainFilter.getSearch())){
			String search = taskMainFilter.getSearch();
			taskMainFilter.setMainName(search);
		}
		//获取当前用户
		String userId = SysUserUtils.getUserId();
		SysUser user = sysUserService.getById(userId);
		SysLogin sysLogin = sysLoginService.getById(userId);
		String roleId = sysLogin.getRoleId();
		List<TaskMain> list = new ArrayList<>();
		//查看当前用户审核过的已完成任务
		taskMainFilter.setAuditorId(userId);
		taskMainFilter.setStatus("4");
		list = taskMainService.queryFilter(taskMainFilter);
		taskMainFilter.setAuditorId(null);
		if ("02".equals(roleId)) {
			//单位领导查看单位所有完成任务
			taskMainFilter.setInspectionId(sysLogin.getDeptId());
			List<TaskMain> list1 = taskMainService.queryFilter(taskMainFilter);
			list.addAll(list1);
			Map<String, TaskMain> mainMap = new HashMap<>();
			for (TaskMain taskMain : list) {
				mainMap.put(taskMain.getSysId(), taskMain);
			}
			list = new ArrayList<TaskMain>(mainMap.values());
		} else {
			//如果都不是.那就只能查看自己的任务
			taskMainFilter.setCreateUser(userId);
			List<TaskMain> list1 = taskMainService.queryFilter(taskMainFilter);
			list.addAll(list1);
		}
		List<TaskMain> taskMainList = new ArrayList<>();
		String deptId = taskMainFilter.getDeptId();
		if (StringUtils.isNotBlank(deptId)) {
			String[] split = deptId.split(",");
			for (String s : split) {
				if (ObjectUtils.isNotBlank(list)) {
					for (TaskMain taskMain : list) {
						List<TaskUnit> taskUnits = taskUnitService.getByMainId(taskMain.getSysId());
						for (TaskUnit taskUnit : taskUnits) {
							if (s.equals(taskUnit.getDeptId())) {
								taskMainList.add(taskMain);
								continue;
							}
						}
					}
				}
			}
			return coverJqGrid(taskMainFilter, taskMainList);
		}else{
			return coverJqGrid(taskMainFilter, list);
		}
	}

	/**
	 * 攻坚完成
	 *
	 * @param taskMainFilter
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/downMainGjian", method = RequestMethod.POST)
	public JqGrid downMainGjian(TaskMainFilter taskMainFilter) {
		if(StringUtils.isNotBlank(taskMainFilter.getSearch())){
			String search = taskMainFilter.getSearch();
			taskMainFilter.setMainName(search);
		}
		String userId = SysUserUtils.getUserId();
		SysLogin sysLogin = sysLoginService.getById(userId);
		SysDept dept = sysDeptService.getById(sysLogin.getDeptId());
		List<TaskMain> list = new ArrayList<>();
		taskMainFilter.setAuditorId(null);
		taskMainFilter.setStatus("4");
		if ("/01/".equals(dept.getDeptRelation()) && dept.getDeptName().startsWith("攻坚")) {
			//攻坚办
			if ("02".equals(sysLogin.getRoleId())) {
				// 所有的攻坚 主任务 都是领导看的
				taskMainFilter.setCrucialUser("ALL");
			} else {
				taskMainFilter.setCrucialUser(userId);
			}
			//查询攻坚系列
			List<TaskMain> listGjian = taskMainService.queryFilter(taskMainFilter);
			list.addAll(listGjian);
		}
		return coverJqGrid(taskMainFilter, list);
	}

	/**
	 * 抄送给县领导的已办事项
	 *
	 * @param filter
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/doneCope", method = RequestMethod.POST)
	public JqGrid DoneCope(TaskMainFilter filter) {
		if(StringUtils.isNotBlank(filter.getSearch())){
			String search = filter.getSearch();
			filter.setMainName(search);
		}
		String userId = SysUserUtils.getUserId();
		filter.setCopeTo(userId);
		List<TaskMain> copeTaskList = copeToService.queryDone(filter);
		return coverJqGrid(filter, copeTaskList);
	}

	/**
	 * 全部任务
	 *
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/allMain", method = RequestMethod.GET)
	public String allMain(Model model) {
		SysUser user = sysUserService.getById(SysUserUtils.getUserId());
		String roleId = SysUserUtils.getRoleId();
		SysDept dept = sysDeptService.getById(SysUserUtils.getDeptId());
		model.addAttribute("dept", dept);
		model.addAttribute("roleId", roleId);
		model.addAttribute("user", user);
		return getView("allMain");
	}

	/**
	 * 督查组全部任务
	 *
	 * @param taskMainFilter
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/allMain", method = RequestMethod.POST)
	public JqGrid allMain(TaskMainFilter taskMainFilter) {
		if(StringUtils.isNotBlank(taskMainFilter.getSearch())){
			String search = taskMainFilter.getSearch();
			taskMainFilter.setMainName(search);
		}
		//获取当前用户
		String userId = SysUserUtils.getUserId();
		SysUser user = sysUserService.getById(userId);
		SysLogin sysLogin = sysLoginService.getById(userId);
		String roleId = sysLogin.getRoleId();
		List<TaskMain> list = new ArrayList<>();
		//查看当前用户审核过的已所有任务
		taskMainFilter.setAuditorId(userId);
		list = taskMainService.queryFilter(taskMainFilter);
		taskMainFilter.setAuditorId(null);
		if ("02".equals(roleId)) {
			//单位领导查看单位所有未完成任务
			taskMainFilter.setInspectionId(sysLogin.getDeptId());
			List<TaskMain> list1 = taskMainService.queryFilter(taskMainFilter);
			list.addAll(list1);
			Map<String, TaskMain> mainMap = new HashMap<>();
			for (TaskMain taskMain : list) {
				mainMap.put(taskMain.getSysId(), taskMain);
			}
			list = new ArrayList<TaskMain>(mainMap.values());
		} else {
			//如果都不是.那就只能查看自己的任务
			taskMainFilter.setCreateUser(userId);
			List<TaskMain> list1 = taskMainService.queryFilter(taskMainFilter);
			list.addAll(list1);
		}
//这里的顺序，是我自己定义的一个List<String>
		String[] regulation = {"3", "0", "2", "4", "1"};
		final List<String> regulationOrder = Arrays.asList(regulation);
//        String[] ordered = {"貂蝉", "诸葛亮", "吕布", "貂蝉", "鲁班", "诸葛亮", "貂蝉", "鲁班", "诸葛亮"};
//        List<String> orderedList = Arrays.asList(ordered);
		Collections.sort(list, new Comparator<TaskMain>() {
			@Override
			public int compare(TaskMain o1, TaskMain o2) {
				int io1 = regulationOrder.indexOf(o1.getStatus());
				int io2 = regulationOrder.indexOf(o2.getStatus());
				return io1 - io2;
			}
		});
		List<TaskMain> taskMainList = new ArrayList<>();
		String deptId = taskMainFilter.getDeptId();
		if (StringUtils.isNotBlank(deptId)) {
			String[] split = deptId.split(",");
			for (String s : split) {
				if (ObjectUtils.isNotBlank(list)) {
					for (TaskMain taskMain : list) {
						List<TaskUnit> taskUnits = taskUnitService.getByMainId(taskMain.getSysId());
						for (TaskUnit taskUnit : taskUnits) {
							if (s.equals(taskUnit.getDeptId())) {
								taskMainList.add(taskMain);
								continue;
							}
						}
					}
				}
			}
			return coverJqGrid(taskMainFilter, taskMainList);
		}else{
			return coverJqGrid(taskMainFilter, list);
		}
	}

	/**
	 * 抄送给县领导的全部事项yan
	 *
	 * @param filter
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/allCope", method = RequestMethod.POST)
	public JqGrid allCope(TaskMainFilter filter) {
		String userId = SysUserUtils.getUserId();
		filter.setCopeTo(userId);
		List<TaskMain> copeTaskList = copeToService.queryAllDone(filter);
		return coverJqGrid(filter, copeTaskList);
	}


	@RequestMapping(value = "/gjquery/{id}",method = RequestMethod.GET)
	public String showGongJianTaskView(Model model,@PathVariable String id)
	{
		/**
		 * id 几个主任务中任意一个主任务的任务Id
		 */
		model.addAttribute("taskMainId", id);
		TaskMain taskMain = taskMainService.getById(id);
		TaskMainBean taskMainBean = new TaskMainBean();
		BeanUtils.copyProperties(taskMain, taskMainBean);
		String[] files = splitString(taskMain.getFile());
		String[] fileNames = splitString(taskMain.getFileName());
		String[] gJFiles = splitString(taskMain.getgJFile());
		String[] gJfileName = splitString(taskMain.getgJFileName());
		String[] resultFiles = splitString(taskMain.getMainResultFile());
		String[] resultFileNames = splitString(taskMain.getMainResultFileName());
		List<Map<String, Object>> fileMapList = new ArrayList<>();
		if (ObjectUtils.isNotBlank(files)) {
			for (int i = 0; i < files.length; i++) {
				Map<String, Object> map = new HashMap<>();
				map.put("file", files[i]);
				map.put("fileName", fileNames[i]);
				fileMapList.add(map);
			}
			taskMainBean.setFiles(fileMapList);
		}
		if (ObjectUtils.isNotBlank(gJFiles)) {
			List<Map<String, Object>> gjFileMapList = new ArrayList<>();
			for (int i = 0; i < gJFiles.length; i++) {
				Map<String, Object> map = new HashMap<>();
				map.put("file", gJFiles[i]);
				map.put("fileName", gJfileName[i]);
				gjFileMapList.add(map);
			}
			taskMainBean.setgJFile(gjFileMapList);
		}
		if (ObjectUtils.isNotBlank(resultFiles)) {
			List<Map<String, Object>> resultFileMapList = new ArrayList<>();
			for (int i = 0; i < resultFiles.length; i++) {
				Map<String, Object> map = new HashMap<>();
				map.put("file", resultFiles[i]);
				map.put("fileName", resultFileNames[i]);
				resultFileMapList.add(map);
			}
			taskMainBean.setMainResultFile(resultFileMapList);
		}

		model.addAttribute("taskMain", taskMainBean);
		/*
			由于所有督查组的轮次都一样，所以只取其中一个组的轮次，
		 */
		SpecialTaskFilter filter = new SpecialTaskFilter();
		filter.setTaskMainId(id);
		List<TaskMajorBean> majorList = specialTaskService.getMajorList(filter);

		if(ObjectUtils.isNotBlank(majorList)){

			TaskMajorBean taskMajorBean = majorList.get(0);
			model.addAttribute("timeRound",taskMajorBean.getTimeRound());
		}else {
			model.addAttribute("timeRound","-");

		}


		model.addAttribute("gjId",taskMain.getGjId());
		//	model.addAttribute("timeRound",)
			return getView("gongjian_query2");

	}

	@RequestMapping(value = "/query2/{id}", method = RequestMethod.GET)
	public String query2(Model model, @PathVariable String id) {
		model.addAttribute("taskMainId", id);
		TaskMain taskMain = taskMainService.getById(id);
		TaskMainBean taskMainBean = new TaskMainBean();
		BeanUtils.copyProperties(taskMain, taskMainBean);
		String[] files = splitString(taskMain.getFile());
		String[] fileNames = splitString(taskMain.getFileName());
		String[] gJFiles = splitString(taskMain.getgJFile());
		String[] gJfileName = splitString(taskMain.getgJFileName());
		String[] resultFiles = splitString(taskMain.getMainResultFile());
		String[] resultFileNames = splitString(taskMain.getMainResultFileName());
		List<Map<String, Object>> fileMapList = new ArrayList<>();
		if (ObjectUtils.isNotBlank(files)) {
			for (int i = 0; i < files.length; i++) {
				Map<String, Object> map = new HashMap<>();
				map.put("file", files[i]);
				map.put("fileName", fileNames[i]);
				fileMapList.add(map);
			}
			taskMainBean.setFiles(fileMapList);
		}
		if (ObjectUtils.isNotBlank(gJFiles)) {
			List<Map<String, Object>> gjFileMapList = new ArrayList<>();
			for (int i = 0; i < gJFiles.length; i++) {
				Map<String, Object> map = new HashMap<>();
				map.put("file", gJFiles[i]);
				map.put("fileName", gJfileName[i]);
				gjFileMapList.add(map);
			}
			taskMainBean.setgJFile(gjFileMapList);
		}
		if (ObjectUtils.isNotBlank(resultFiles)) {
			List<Map<String, Object>> resultFileMapList = new ArrayList<>();
			for (int i = 0; i < resultFiles.length; i++) {
				Map<String, Object> map = new HashMap<>();
				map.put("file", resultFiles[i]);
				map.put("fileName", resultFileNames[i]);
				resultFileMapList.add(map);
			}
			taskMainBean.setMainResultFile(resultFileMapList);
		}

		model.addAttribute("taskMain", taskMainBean);
		String roleId = SysUserUtils.getRoleId();
		SysDept dept = deptService.getById(SysUserUtils.getDeptId());
		model.addAttribute("roleId", roleId);

		if (StringUtils.isNotBlank(taskMain.getOverdueDept())) {
			//修改逻辑，如果是重大立项，打开另外的重大单位页面；

           /* //如果不为空，单位重大事项，查看后将状态改为在办
            if (!"4".equals(taskMain.getStatus())) {
                taskMain.setOverdueDeptState("1");
                taskMainService.update(taskMain);
            }*/


			SysDept overdueDept = deptService.getById(taskMain.getOverdueDept());
			model.addAttribute("overdueDept", overdueDept);

			//判断是否是督办单位
			String userId = SysUserUtils.getUserId();


			SysUser loginUser = sysUserService.getById(userId);

			String personSignal = loginUser.getPersonSignal();
			String loginDeptId = SysUserUtils.getDeptId();


			List<TaskUnit> taskUnitList = taskUnitService.getByMainId(taskMain.getSysId());

			model.addAttribute("taskUnit",taskUnitList);

			if("1".equals(personSignal)&&  taskMain.getOverdueDept().trim().equals(loginDeptId.trim())){
			//去特殊情况表找到这条督办 设置为待反馈
				SpecialTaskFilter speFilter = new SpecialTaskFilter();
				speFilter.setTaskMainId(taskMain.getSysId());
				speFilter.setOverdueDeptId(taskMain.getOverdueDept());
				List<SpecialTask> specialTasks = specialTaskService.queryFilter(speFilter);
				SpecialTask specialTask = specialTasks.get(0);
				if("0".equals(specialTask.getType()))
				{
					specialTask.setType("1");
					specialTaskService.update(specialTask);
				}
				return getView("zd_db_query");
			}
			return getView("zd_Query");



		}
		if ("20190722100000000194".equals(dept.getSysId())) {
			//如果是攻坚作战室单位，当查看该任务后，该任务就不是在办
			taskMain.setCrucialState(null);
			taskMainService.update(taskMain);
		}
		model.addAttribute("dept", dept);

		return getView("query2");
	}


	/**
	 * 根据攻坚id获取攻坚任务
	 * @param filter
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/gjmaintask/",method = RequestMethod.POST)
	public JqGrid getGongJianTask(TaskMainFilter filter)
	{
		String gjId = filter.getGjId();

		TaskMainFilter gjFilter = new TaskMainFilter();
		gjFilter.setGjId(gjId);
		List<TaskMain> taskMains = taskMainService.queryFilter(gjFilter);
		//处理单位
		List<TaskMainFilter> list = new ArrayList<>();
		for (TaskMain item : taskMains) {
			TaskMainFilter data = new TaskMainFilter();
			BeanUtils.copyProperties(item,data);
			String strDept = redisService.get("dept:" + item.getInspectionId());
			try {
				SysDept sysDept = JSONObject.parseObject(strDept, SysDept.class);
				data.setDeptName(sysDept.getDeptName());
			}catch (Exception e){
				data.setDeptName("未知错误");
			}
			list.add(data);
		}

		return coverJqGrid(filter,list);

	}



	/**
	 * 返回主任务二级页面,单位任务
	 *
	 * @param filter
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/query2", method = RequestMethod.POST)
	public JqGrid unitTask(TaskUnitFilter filter) {
		if (StringUtils.isNotBlank(filter.getSearch())){
			String search = filter.getSearch();
			filter.setTaskSubName(search);
		}
//         List<TaskUnit> taskUnits = taskUnitService.queryFilter(filter);
		//List<TaskUnit> taskUnits = taskUnitService.queryTaskUnit(filter);
		List<TaskUnit> taskUnits = taskUnitService.getQianTouTask(filter);
		return coverJqGrid(filter, taskUnits);
	}

	/**
	 * 查看主任务所有单位任务(查看按钮)
	 *
	 * @param filter
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/allUnit", method = RequestMethod.POST)
	public JqGrid allUnit(TaskUnitFilter filter) {
		List<TaskUnit> allTaskUnit = taskUnitService.getAllTaskUnit(filter);
		return coverJqGrid(filter, allTaskUnit);
	}

	/**
	 * 抄送主任务打开的二级页面
	 *
	 * @param model
	 * @param taskMainId
	 * @return
	 */
	@RequestMapping(value = "/copeUnit/{taskMainId}")
	public String copeUnit(Model model, @PathVariable String taskMainId) {
		String userId = SysUserUtils.getUserId();
		TaskMain taskMain = taskMainService.getById(taskMainId);
		model.addAttribute("taskMainId", taskMainId);
		model.addAttribute("taskMain", taskMain);
		return getView("copeUnit");
	}

	/**
	 * 抄送二级列表
	 *
	 * @param filter
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/copeUnit", method = RequestMethod.POST)
	public JqGrid copeUnit(TaskUnitFilter filter) {
		List<TaskUnit> copeUnit = taskUnitService.updateCopeTaskUnit(filter);
		return coverJqGrid(filter, copeUnit);
	}

	/**
	 * 事项类型id转name
	 *
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/categoryName/{id}")
	public TaskCategory categoryName(@PathVariable String id) {
		TaskCategory category = taskCategoryService.getById(id);
		return category;
	}


	@ResponseBody
	@RequestMapping(value = "/deptList", method = RequestMethod.POST)
	public List<SysDept> deptList(String deptRelation) {
		List<SysDept> deptList = deptService.queryDeptList(deptRelation);
		return deptList;
	}

	/** 已反馈 未反馈 未签收接口详情
	 * 单位任务详情页面
	 *
	 * @param taskUnitId
	 * @return
	 */
	@RequestMapping(value = "/unitDetail/{taskUnitId}", method = RequestMethod.GET)
	public String unitDetail(Model model, @PathVariable String taskUnitId) {
		//已反馈单位
		StringBuffer feedBacks = new StringBuffer();
		//未反馈单位
		StringBuffer noFeedBacks = new StringBuffer();

		String userId = SysUserUtils.getUserId();
		TaskUnit taskUnit = taskUnitService.getById(taskUnitId);
		TaskMain taskMain = taskMainService.getById(taskUnit.getTaskMainId());
		TaskSub taskSub = taskSubService.getById(taskUnit.getTaskSubId());

		TaskBackNewFilter filter0 = new TaskBackNewFilter();
		filter0.setTaskSubId(taskUnit.getTaskSubId());
		List<TaskBackNew> allBackNewList = taskBackNewService.queryAll(filter0);

		TaskSubBean taskSubBean = new TaskSubBean();
		BeanUtils.copyProperties(taskSub, taskSubBean);
		String[] files = splitString(taskSub.getSubSituationFile());
		String[] fileNames = splitString(taskSub.getFileName());
		List<Map<String, Object>> fileMapList = new ArrayList<>();
		if (ObjectUtils.isNotBlank(files)) {
			for (int i = 0; i < files.length; i++) {
				Map<String, Object> map = new HashMap<>();
				map.put("file", files[i]);
				map.put("fileName", fileNames[i]);
				fileMapList.add(map);
			}
			taskSubBean.setSubSituationFile(fileMapList);
		}
		List<TaskLogNew> logNewList = taskLogNewService.getByUnitId(taskUnitId);
		String taskSubName = taskUnit.getTaskSubName();
		//查看当前任务反馈给我的信
		//List<TaskBackNew> taskBackNewList = new ArrayList<>();
		List<TaskBackNewBean> taskBackNewBeanList = new ArrayList<>();
		//不为空，说明是单位重大任务；
		//判断是否是 督办单位
		//督办单位 取出该子任务下所有牵头单位的反馈；
		if(StringUtils.isNotBlank(taskMain.getOverdueDept())){
			TaskBackNewFilter filter = new TaskBackNewFilter();
			filter.setTaskSubId(taskSub.getSysId());
			filter.setDeptType("1");//1牵头 2协办，3 督办单位；
			//所有牵头单位的 反馈
			List<TaskBackNew> taskBackNews = taskBackNewService.queryAll(filter);
			for (TaskBackNew taskBackNew : taskBackNews) {
				TaskBackNewBean taskBackNewBean = new TaskBackNewBean();
				BeanUtils.copyProperties(taskBackNew, taskBackNewBean);
				String[] file = splitString(taskBackNew.getFile());
				String[] fileName = splitString(taskBackNew.getFileName());
				List<Map<String, Object>> backFileList = new ArrayList<>();
				if (ObjectUtils.isNotBlank(file)) {

					for (int i = 0; i < file.length; i++) {
						Map<String, Object> map = new HashMap<>();
						map.put("file", file[i]);
						map.put("fileName", fileName[i]);
						backFileList.add(map);
					}
				}
				taskBackNewBean.setFiles(backFileList);
				taskBackNewBeanList.add(taskBackNewBean);
			}

		}else {

			SysDept dept = deptService.getById(taskUnit.getDeptId());
			SysUserFilter userFilter = new SysUserFilter();
			userFilter.setDeptId(dept.getSysId());
			userFilter.setRoleId("02");

			List<SysLogin> loginList = sysLoginService.queryUserLoginByRoleDept(userFilter);
			for (SysLogin sysLogin : loginList) {
				List<TaskBackNew> taskBackNews = taskBackNewService.getByTaskUnitIdAndSenderId(taskUnit.getSysId(), sysLogin.getSysId());
				//taskBackNewList.addAll(taskBackNews);
				for (TaskBackNew taskBackNew : taskBackNews) {
					TaskBackNewBean taskBackNewBean = new TaskBackNewBean();
					BeanUtils.copyProperties(taskBackNew, taskBackNewBean);
					String[] file = splitString(taskBackNew.getFile());
					String[] fileName = splitString(taskBackNew.getFileName());
					List<Map<String, Object>> backFileList = new ArrayList<>();
					if (ObjectUtils.isNotBlank(file)) {

						for (int i = 0; i < file.length; i++) {
							Map<String, Object> map = new HashMap<>();
							map.put("file", file[i]);
							map.put("fileName", fileName[i]);
							backFileList.add(map);
						}
					}
					taskBackNewBean.setFiles(backFileList);
					taskBackNewBeanList.add(taskBackNewBean);
				}
			}


		}

//        List<TaskBackNew> taskBackNewList = taskBackNewService.getByTaskUnitIdAndRecipientId(taskUnitId, userId);
		//督查角色查看当前单位主要领导 的反馈信息

		//当前单位任务领导是否有批示信息
		//查询当前任务是否有抄送,当前主任务的抄送领导
		List<HastenMessage> leaderMessages = new ArrayList<>();
		List<CopeTo> copeTos = copeToService.getByTaskMainId(taskMain.getSysId());
		if (ObjectUtils.isNotBlank(copeTos)) {
			for (CopeTo copeTo : copeTos) {
				String leaderId = copeTo.getLeaderId();
				//查看当前领导对当前单位任务有没有批示信息
				HastenMessageFilter filter = new HastenMessageFilter();
				filter.setCreateId(leaderId);
				filter.setTaskUnitId(taskUnitId);
				List<HastenMessage> messages = hastenMessageService.queryFilter(filter);
				if (ObjectUtils.isNotBlank(messages)) {
					leaderMessages.addAll(messages);
				}
			}
		}
		//牵头单位名称集合
		String leadDepts = "";
		List<TaskUnit> leadDeptList = taskUnitService.getBySubIdAndUnitType(taskUnit.getTaskSubId(), "1", taskUnit.getTimeRound());
		for (TaskUnit unit : leadDeptList) {
			leadDepts += (unit.getDeptName() + " ");
			boolean flag = false;
			for (TaskBackNew bean : allBackNewList) {
				if (unit.getDeptName().equals(bean.getSenderName())) {
					flag = true;
					break;
				}
			}
			if (flag) {
				if (feedBacks.length() > 0) {
					feedBacks.append("、" + unit.getDeptName());
				} else {
					feedBacks.append(unit.getDeptName());
				}
			} else {
				if (noFeedBacks.length() > 0) {
					noFeedBacks.append("、" + unit.getDeptName());
				} else {
					noFeedBacks.append(unit.getDeptName());
				}
			}

		}
		//协办单位名称集合
		List<TaskUnit> xbDeptList = taskUnitService.getBySubIdAndUnitType(taskUnit.getTaskSubId(), "2", taskUnit.getTimeRound());
		for (TaskUnit unit : xbDeptList) {
			boolean flag = false;
			for (TaskBackNew bean : allBackNewList) {
				if (unit.getDeptName().equals(bean.getSenderName())) {
					flag = true;
					break;
				}
			}
			if (flag) {
				if (feedBacks.length() > 0) {
					feedBacks.append("、" + unit.getDeptName());
				} else {
					feedBacks.append(unit.getDeptName());
				}
			} else {
				if (noFeedBacks.length() > 0) {
					noFeedBacks.append("、" + unit.getDeptName());
				} else {
					noFeedBacks.append(unit.getDeptName());
				}
			}
		}

		//历史轮次
		List<Map<String, Object>> oldTask = new ArrayList<>();
		oldTask = taskUnitService.getByOldTaskUnit(taskUnit.getTaskSubId(), taskUnit.getDeptId());
		model.addAttribute("oldTask", oldTask);
		//抄送领导给当前单位的批示信息
		model.addAttribute("leaderMessages", leaderMessages);
		//单位任务实体类
		model.addAttribute("taskUnit", taskUnit);
		model.addAttribute("taskBackNewList", taskBackNewBeanList);
		model.addAttribute("taskSubName", taskSubName);
		model.addAttribute("taskSub", taskSubBean);
		model.addAttribute("mainName", taskMain.getMainName());
		model.addAttribute("logNewList", logNewList);
		//新增
		TaskMainBean taskMainBean = new TaskMainBean();
		BeanUtils.copyProperties(taskMain, taskMainBean);
		String[] files1 = splitString(taskMain.getFile());
		String[] fileNames1 = splitString(taskMain.getFileName());
		String[] gJFiles = splitString(taskMain.getgJFile());
		String[] gJfileName = splitString(taskMain.getgJFileName());
		String[] resultFiles = splitString(taskMain.getMainResultFile());
		String[] resultFileNames = splitString(taskMain.getMainResultFileName());
		List<Map<String, Object>> fileMapList1 = new ArrayList<>();
		if (ObjectUtils.isNotBlank(files1)) {
			for (int i = 0; i < files1.length; i++) {
				Map<String, Object> map = new HashMap<>();
				map.put("file", files1[i]);
				map.put("fileName", fileNames1[i]);
				fileMapList1.add(map);
			}
			taskMainBean.setFiles(fileMapList1);
		}
		if (ObjectUtils.isNotBlank(gJFiles)) {
			List<Map<String, Object>> gjFileMapList = new ArrayList<>();
			for (int i = 0; i < gJFiles.length; i++) {
				Map<String, Object> map = new HashMap<>();
				map.put("file", gJFiles[i]);
				map.put("fileName", gJfileName[i]);
				gjFileMapList.add(map);
			}
			taskMainBean.setgJFile(gjFileMapList);
		}
		if (ObjectUtils.isNotBlank(resultFiles)) {
			List<Map<String, Object>> resultFileMapList = new ArrayList<>();
			for (int i = 0; i < resultFiles.length; i++) {
				Map<String, Object> map = new HashMap<>();
				map.put("file", resultFiles[i]);
				map.put("fileName", resultFileNames[i]);
				resultFileMapList.add(map);
			}
			taskMainBean.setMainResultFile(resultFileMapList);
		}
		model.addAttribute("taskMain", taskMainBean);
		model.addAttribute("xbDeptList", xbDeptList);
		model.addAttribute("leadDepts", leadDepts);
		model.addAttribute("feedBacks", feedBacks.toString());
		model.addAttribute("noFeedBacks", noFeedBacks.toString());
		return getView("details");
	}

	/**
	 * 主任务的反馈列表
	 * @param model
	 * @param taskUnitId
	 * @return
	 */
	@RequestMapping(value = "/mainunitDetail/{taskUnitId}", method = RequestMethod.GET)
	public String mainunitDetail(Model model, @PathVariable String taskUnitId) {
		//已反馈单位
		StringBuffer feedBacks = new StringBuffer();
		//未反馈单位
		StringBuffer noFeedBacks = new StringBuffer();

		String userId = SysUserUtils.getUserId();
		TaskUnit taskUnit = taskUnitService.getById(taskUnitId);
		TaskMain taskMain = taskMainService.getById(taskUnit.getTaskMainId());
		TaskSub taskSub = taskSubService.getById(taskUnit.getTaskSubId());

		TaskBackNewFilter filter0 = new TaskBackNewFilter();
		filter0.setTaskSubId(taskUnit.getTaskSubId());
		List<TaskBackNew> allBackNewList = taskBackNewService.queryAll(filter0);

		TaskSubBean taskSubBean = new TaskSubBean();
		BeanUtils.copyProperties(taskSub, taskSubBean);
		String[] files = splitString(taskSub.getSubSituationFile());
		String[] fileNames = splitString(taskSub.getFileName());
		List<Map<String, Object>> fileMapList = new ArrayList<>();
		if (ObjectUtils.isNotBlank(files)) {
			for (int i = 0; i < files.length; i++) {
				Map<String, Object> map = new HashMap<>();
				map.put("file", files[i]);
				map.put("fileName", fileNames[i]);
				fileMapList.add(map);
			}
			taskSubBean.setSubSituationFile(fileMapList);
		}
		List<TaskLogNew> logNewList = taskLogNewService.getByUnitId(taskUnitId);
		String taskSubName = taskUnit.getTaskSubName();
		//查看当前任务反馈给我的信
		//List<TaskBackNew> taskBackNewList = new ArrayList<>();
		List<TaskBackNewBean> taskBackNewBeanList = new ArrayList<>();
		//不为空，说明是单位重大任务；
		//判断是否是 督办单位
		//督办单位 取出该子任务下所有牵头单位的反馈；
		if(StringUtils.isNotBlank(taskMain.getOverdueDept())){
			TaskBackNewFilter filter = new TaskBackNewFilter();
			filter.setTaskSubId(taskSub.getSysId());
			filter.setDeptType("1");//1牵头 2协办，3 督办单位；
			//所有牵头单位的 反馈
			List<TaskBackNew> taskBackNews = taskBackNewService.queryAll(filter);
			for (TaskBackNew taskBackNew : taskBackNews) {
				TaskBackNewBean taskBackNewBean = new TaskBackNewBean();
				BeanUtils.copyProperties(taskBackNew, taskBackNewBean);
				String[] file = splitString(taskBackNew.getFile());
				String[] fileName = splitString(taskBackNew.getFileName());
				List<Map<String, Object>> backFileList = new ArrayList<>();
				if (ObjectUtils.isNotBlank(file)) {

					for (int i = 0; i < file.length; i++) {
						Map<String, Object> map = new HashMap<>();
						map.put("file", file[i]);
						map.put("fileName", fileName[i]);
						backFileList.add(map);
					}
				}
				taskBackNewBean.setFiles(backFileList);
				taskBackNewBeanList.add(taskBackNewBean);
			}

		}else {

			SysDept dept = deptService.getById(taskUnit.getDeptId());
			SysUserFilter userFilter = new SysUserFilter();
			userFilter.setDeptId(dept.getSysId());
			userFilter.setRoleId("02");
			for (TaskBackNew taskBackNew : allBackNewList) {
					TaskBackNewBean taskBackNewBean = new TaskBackNewBean();
					BeanUtils.copyProperties(taskBackNew, taskBackNewBean);
					String[] file = splitString(taskBackNew.getFile());
					String[] fileName = splitString(taskBackNew.getFileName());
					List<Map<String, Object>> backFileList = new ArrayList<>();
					if (ObjectUtils.isNotBlank(file)) {

						for (int i = 0; i < file.length; i++) {
							Map<String, Object> map = new HashMap<>();
							map.put("file", file[i]);
							map.put("fileName", fileName[i]);
							backFileList.add(map);
						}
					}
					taskBackNewBean.setFiles(backFileList);
					taskBackNewBeanList.add(taskBackNewBean);
			}
			


			/*List<SysLogin> loginList = sysLoginService.queryUserLoginByRoleDept(userFilter);
			for (SysLogin sysLogin : loginList) {
				List<TaskBackNew> taskBackNews = taskBackNewService.getByTaskUnitIdAndSenderId(taskUnit.getSysId(), sysLogin.getSysId());
				//taskBackNewList.addAll(taskBackNews);
				for (TaskBackNew taskBackNew : taskBackNews) {
					TaskBackNewBean taskBackNewBean = new TaskBackNewBean();
					BeanUtils.copyProperties(taskBackNew, taskBackNewBean);
					String[] file = splitString(taskBackNew.getFile());
					String[] fileName = splitString(taskBackNew.getFileName());
					List<Map<String, Object>> backFileList = new ArrayList<>();
					if (ObjectUtils.isNotBlank(file)) {

						for (int i = 0; i < file.length; i++) {
							Map<String, Object> map = new HashMap<>();
							map.put("file", file[i]);
							map.put("fileName", fileName[i]);
							backFileList.add(map);
						}
					}
					taskBackNewBean.setFiles(backFileList);
					taskBackNewBeanList.add(taskBackNewBean);
				}
			}*/


		}

//        List<TaskBackNew> taskBackNewList = taskBackNewService.getByTaskUnitIdAndRecipientId(taskUnitId, userId);
		//督查角色查看当前单位主要领导 的反馈信息

		//当前单位任务领导是否有批示信息
		//查询当前任务是否有抄送,当前主任务的抄送领导
		List<HastenMessage> leaderMessages = new ArrayList<>();
		List<CopeTo> copeTos = copeToService.getByTaskMainId(taskMain.getSysId());
		if (ObjectUtils.isNotBlank(copeTos)) {
			for (CopeTo copeTo : copeTos) {
				String leaderId = copeTo.getLeaderId();
				//查看当前领导对当前单位任务有没有批示信息
				HastenMessageFilter filter = new HastenMessageFilter();
				filter.setCreateId(leaderId);
				filter.setTaskUnitId(taskUnitId);
				List<HastenMessage> messages = hastenMessageService.queryFilter(filter);
				if (ObjectUtils.isNotBlank(messages)) {
					leaderMessages.addAll(messages);
				}
			}
		}
		//牵头单位名称集合
		String leadDepts = "";
		List<TaskUnit> leadDeptList = taskUnitService.getBySubIdAndUnitType(taskUnit.getTaskSubId(), "1", taskUnit.getTimeRound());
		for (TaskUnit unit : leadDeptList) {
			leadDepts += (unit.getDeptName() + " ");
			boolean flag = false;
			for (TaskBackNew bean : allBackNewList) {
				if (unit.getDeptName().equals(bean.getSenderName())) {
					flag = true;
					break;
				}
			}
			if (flag) {
				if (feedBacks.length() > 0) {
					feedBacks.append("、" + unit.getDeptName());
				} else {
					feedBacks.append(unit.getDeptName());
				}
			} else {
				if (noFeedBacks.length() > 0) {
					noFeedBacks.append("、" + unit.getDeptName());
				} else {
					noFeedBacks.append(unit.getDeptName());
				}
			}

		}
		//协办单位名称集合
		List<TaskUnit> xbDeptList = taskUnitService.getBySubIdAndUnitType(taskUnit.getTaskSubId(), "2", taskUnit.getTimeRound());
		for (TaskUnit unit : xbDeptList) {
			boolean flag = false;
			for (TaskBackNew bean : allBackNewList) {
				if (unit.getDeptName().equals(bean.getSenderName())) {
					flag = true;
					break;
				}
			}
			if (flag) {
				if (feedBacks.length() > 0) {
					feedBacks.append("、" + unit.getDeptName());
				} else {
					feedBacks.append(unit.getDeptName());
				}
			} else {
				if (noFeedBacks.length() > 0) {
					noFeedBacks.append("、" + unit.getDeptName());
				} else {
					noFeedBacks.append(unit.getDeptName());
				}
			}
		}

		//历史轮次
		List<Map<String, Object>> oldTask = new ArrayList<>();
		oldTask = taskUnitService.getByOldTaskUnit(taskUnit.getTaskSubId(), taskUnit.getDeptId());
		model.addAttribute("oldTask", oldTask);
		//抄送领导给当前单位的批示信息
		model.addAttribute("leaderMessages", leaderMessages);
		//单位任务实体类
		model.addAttribute("taskUnit", taskUnit);
		model.addAttribute("taskBackNewList", taskBackNewBeanList);
		model.addAttribute("taskSubName", taskSubName);
		model.addAttribute("taskSub", taskSubBean);
		model.addAttribute("mainName", taskMain.getMainName());
		model.addAttribute("logNewList", logNewList);
		//新增
		TaskMainBean taskMainBean = new TaskMainBean();
		BeanUtils.copyProperties(taskMain, taskMainBean);
		String[] files1 = splitString(taskMain.getFile());
		String[] fileNames1 = splitString(taskMain.getFileName());
		String[] gJFiles = splitString(taskMain.getgJFile());
		String[] gJfileName = splitString(taskMain.getgJFileName());
		String[] resultFiles = splitString(taskMain.getMainResultFile());
		String[] resultFileNames = splitString(taskMain.getMainResultFileName());
		List<Map<String, Object>> fileMapList1 = new ArrayList<>();
		if (ObjectUtils.isNotBlank(files1)) {
			for (int i = 0; i < files1.length; i++) {
				Map<String, Object> map = new HashMap<>();
				map.put("file", files1[i]);
				map.put("fileName", fileNames1[i]);
				fileMapList1.add(map);
			}
			taskMainBean.setFiles(fileMapList1);
		}
		if (ObjectUtils.isNotBlank(gJFiles)) {
			List<Map<String, Object>> gjFileMapList = new ArrayList<>();
			for (int i = 0; i < gJFiles.length; i++) {
				Map<String, Object> map = new HashMap<>();
				map.put("file", gJFiles[i]);
				map.put("fileName", gJfileName[i]);
				gjFileMapList.add(map);
			}
			taskMainBean.setgJFile(gjFileMapList);
		}
		if (ObjectUtils.isNotBlank(resultFiles)) {
			List<Map<String, Object>> resultFileMapList = new ArrayList<>();
			for (int i = 0; i < resultFiles.length; i++) {
				Map<String, Object> map = new HashMap<>();
				map.put("file", resultFiles[i]);
				map.put("fileName", resultFileNames[i]);
				resultFileMapList.add(map);
			}
			taskMainBean.setMainResultFile(resultFileMapList);
		}
		model.addAttribute("taskMain", taskMainBean);
		model.addAttribute("xbDeptList", xbDeptList);
		model.addAttribute("leadDepts", leadDepts);
		model.addAttribute("feedBacks", feedBacks.toString());
		model.addAttribute("noFeedBacks", noFeedBacks.toString());
		return getView("details");
	}


	/**
	 * 修改单位任务
	 *
	 * @param taskUnitId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getTaskUnit/{taskUnitId}")
	public Message getTaskUnit(@PathVariable String taskUnitId) {
		TaskUnit taskUnit = taskUnitService.getById(taskUnitId);
		if (ObjectUtils.isBlank(taskUnit)) {
			return coverMessage("500");
		} else {
			return coverMessage("200", "success", taskUnit);
		}
	}

	@ResponseBody
	@RequestMapping(value = "editTaskUnit", method = RequestMethod.POST)
	public Message editTaskUnit(TaskSubFilter filter) {
		//处理时间格式；
		String timeType = filter.getTimeType();
		String timeLimit = filter.getSubTimeLimit();
		int  code =1;
		try {
			code = excelDataService.setTimetypeAndLimint(filter, timeType, timeLimit);
		}catch (Exception e)
		{
			return  coverMessage("500","时间格式参数错误");
		}
		if(code==0)
		{
			return  coverMessage("500","时间格式参数错误");
		}



		TaskUnit taskUnit = taskUnitService.getById(filter.getSysId());
		String taskSubId = taskUnit.getTaskSubId();
		TaskSub taskSubEntity = taskSubService.getById(taskSubId);
		taskSubEntity.setSubTimeLimit(filter.getSubTimeLimit());
		taskSubEntity.setTimeType(filter.getTimeType());
		taskSubEntity.setPeriod(filter.getPeriod());
		taskSubEntity.setDay(filter.getDay());
		taskSubEntity.setWeek(filter.getWeek());
		taskSubEntity.setMonth(filter.getMonth());
		taskSubEntity.setQuarter(filter.getMonth());
		taskSubEntity.setTimeLimits(filter.getTimeLimits());

		// 设置底下的单位任务；
		TaskUnitFilter unitFilter = new TaskUnitFilter();
		unitFilter.setTaskSubId(taskSubEntity.getSysId());
		List<TaskUnit> taskUnits = taskUnitService.queryListUnit(unitFilter);
		taskUnits.forEach(o->{
			o.setTimeLimit(filter.getSubTimeLimit());
			o.setTimeType(filter.getTimeType());
			o.setPeriod(filter.getPeriod());
			o.setDay(filter.getDay());
			o.setWeek(filter.getWeek());
			o.setMonth(filter.getMonth());
			o.setQuarter(filter.getMonth());
			o.setTimeLimits(filter.getTimeLimits());
		});


		taskSubService.update(taskSubEntity);
		taskUnitService.batchUpdate(taskUnits);
		//taskUnit.setTimeLimit(filter.getTimeLimit());
		//taskUnitService.update(taskUnit);
		return coverMessage("200");
	}

	/**
	 * 督查处理反馈结果
	 *
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/updateBackNew", method = RequestMethod.POST)
	public String updateBackNew(TaskBackNewFilter backNewFilter) {
		//userId 登录id   comment。评价   end 结束周期   status  。。是否办结
		String s = taskMainService.updateBackNew(backNewFilter);
		if ("200".equals(s)) {
			return "200";
		} else {
			return "500";
		}
	}



	/**
	 * 子任务反馈汇总
	 *
	 * @param model
	 * @param taskUnitId
	 * @return
	 */
	@RequestMapping(value = "/collect/{taskUnitId}", method = RequestMethod.GET)
	public String collect(Model model, @PathVariable String taskUnitId) {
		//当前单位任务
		TaskUnit taskUnit = taskUnitService.getById(taskUnitId);
		//根据当前任务的子任务id和接收人id查询反馈信息
        List<TaskBackNewBean> taskBackNewBeanList=new ArrayList<>();
        List<TaskBackNew> taskBackNews = taskBackNewService.getByRecipientIdAndSubId(SysUserUtils.getUserId(), taskUnit.getTaskSubId());
        TaskBackNewBean taskBackNewBean = new TaskBackNewBean();
        for (TaskBackNew taskBackNew : taskBackNews) {
            BeanUtils.copyProperties(taskBackNew, taskBackNewBean);
            String[] file = splitString(taskBackNew.getFile());
            String[] fileName = splitString(taskBackNew.getFileName());
            List<Map<String, Object>> backFileList = new ArrayList<>();
            if (ObjectUtils.isNotBlank(file)) {
                for (int i = 0; i < file.length; i++) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("file", file[i]);
                    map.put("fileName", fileName[i]);
                    backFileList.add(map);
                }
            }
            taskBackNewBean.setFiles(backFileList);
            taskBackNewBeanList.add(taskBackNewBean);
        }
		//当前汇总的子任务
		TaskSub taskSub = taskSubService.getById(taskUnit.getTaskSubId());
        TaskSubBean taskSubBean = new TaskSubBean();
        BeanUtils.copyProperties(taskSub, taskSubBean);
        String[] files = splitString(taskSub.getSubSituationFile());
        String[] fileNames = splitString(taskSub.getFileName());
        List<Map<String, Object>> fileMapList = new ArrayList<>();
        if (ObjectUtils.isNotBlank(files)) {
            for (int i = 0; i < files.length; i++) {
                Map<String, Object> map = new HashMap<>();
                map.put("file", files[i]);
                map.put("fileName", fileNames[i]);
                fileMapList.add(map);
            }
            taskSubBean.setSubSituationFile(fileMapList);
        }
		model.addAttribute("taskSub", taskSubBean);
		model.addAttribute("taskBackNews", taskBackNewBeanList);
		return getView("collect");
	}

	/**
	 * 保存汇总信息
	 *
	 * @param filter
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/collect", method = RequestMethod.POST)
	public String collect(TaskSubFilter filter) {
		TaskSub taskSub = taskSubService.getById(filter.getSysId());
		taskSub.setSubSituation(filter.getSubSituation());
		taskSub.setSubProblem(filter.getSubProblem());
		taskSub.setSubPlan(filter.getSubPlan());
		String subSituationFile = taskSub.getSubSituationFile();
		String fileName = taskSub.getFileName();
		String files="";
		String fileNames="";
		if (StringUtils.isNotBlank(subSituationFile)){
			String[] file1 = splitString(subSituationFile);
			String[] fileName1 = splitString(fileName);
			for (String string : file1) {
				if(StringUtils.isNotBlank(string)){
					files+=string+",";
				}
			}
			for (String string : fileName1) {
				if(StringUtils.isNotBlank(string)){
					fileNames+=string+",";
				}
			}
			files=files+filter.getSubSituationFile();
			fileNames=fileNames+filter.getFileName();
		}else{
			files=filter.getSubSituationFile();
			fileNames=filter.getFileName();
		}
		taskSub.setSubSituationFile(files);
		taskSub.setFileName(fileNames);
		taskSubService.update(taskSub);
		return "200";
	}

	/**
	 * 攻坚任务反馈督查组反馈至攻坚办
	 *
	 * @param filter
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/saveMainResult", method = RequestMethod.POST)
	public Message saveMainResult(TaskMainFilter filter) {
		TaskMain taskMain = taskMainService.getById(filter.getSysId());
		String mainResultFile = "";
		String mainResultFileName="";
		if (StringUtils.isBlank(taskMain.getMainResultFile())&&StringUtils.isBlank(filter.getMainResultFile())){
			return coverMessage("500", "请上传汇总附件");
		}else if (StringUtils.isBlank(taskMain.getMainResultFile())){
			 mainResultFile = filter.getMainResultFile();
			 mainResultFileName = filter.getMainResultFileName();
			}else if (StringUtils.isBlank(filter.getMainResultFile())) {
			 mainResultFile = ","+taskMain.getMainResultFile();
			 mainResultFileName =","+ taskMain.getMainResultFileName();
		}else{
			String[] file1 = splitString(taskMain.getMainResultFile());
			String[] fileName1 = splitString(taskMain.getMainResultFileName());
			for (String string : file1) {
				if(StringUtils.isNotBlank(string)){
					mainResultFile+=string+",";
				}
			}
			for (String string : fileName1) {
				if(StringUtils.isNotBlank(string)){
					mainResultFileName+=string+",";
				}
			}
			 mainResultFile =mainResultFile+filter.getMainResultFile();
			 mainResultFileName =mainResultFileName+filter.getMainResultFileName();
		}
		taskMain.setMainResult(filter.getMainResult());
		taskMain.setMainResultFile(mainResultFile);
		taskMain.setMainResultFileName(mainResultFileName);
		//设置攻坚作战室的任务为待办任务；
		taskMain.setCrucialState("0");
		taskMainService.update(taskMain);
		return coverMessage("200", "反馈成功");
	}

	/**
	 * 打开催办输入页面
	 *
	 * @param model
	 * @param taskUnitId
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/urgeModel/{taskUnitId}")
	public Set<SysUser> urgeModel(Model model, @PathVariable String taskUnitId) {
		//新建一个set集合存放要返回的用户信息集合
		Set<SysUser> sysUsers = new HashSet<>();
//        List<SysUser> userList =new ArrayList<>();
		//当前催办的单位任务
		TaskUnit taskUnit = taskUnitService.getById(taskUnitId);
		//当前任务承办单位
		SysDept dept = deptService.getById(taskUnit.getDeptId());
		//根据当前单位任务id查询是否有批转
		List<TaskUser> taskUserList = taskUserService.getByTaskUnitId(taskUnitId);
		if (ObjectUtils.isBlank(taskUserList)) {
			//没有批转过,查询当前单位主要领导的信息
			SysUserFilter userFilter = new SysUserFilter();
			userFilter.setRoleId("02");
			userFilter.setDeptId(dept.getSysId());
			List<SysLogin> loginList = sysLoginService.queryUserLoginByRoleDept(userFilter);
			for (SysLogin sysLogin : loginList) {
				SysUser user = sysUserService.getById(sysLogin.getSysId());
				sysUsers.add(user);
			}
		} else {
			//主要领导已经批转给单位人员。查询当前批转给当前单位人员的任务
			for (TaskUser taskUser : taskUserList) {
				//当前单位人员任务的userid
				SysLogin login = sysLoginService.getById(taskUser.getUnitUserId());
				//判断当前用户是否是分管
				if ("03".equals(login.getRoleId())) {
					//如果是分管，判断他是否批转过这个单位任务
					//根据人员任务创建的 id 判断分管是否有批转下去
					List<TaskUser> taskUsers = taskUserService.getByCreateUserAndTaskUnitId(taskUnitId, login.getSysId());
					if (ObjectUtils.isBlank(taskUsers)) {
						//没有批转过就返回当前分管的信息
						SysUser fgUser = sysUserService.getById(login.getSysId());
						sysUsers.add(fgUser);
					} else {
						//如果批转过就添加批转了的人员的信息
						for (TaskUser user : taskUsers) {
							SysUser jbUser = sysUserService.getById(user.getUnitUserId());
							sysUsers.add(jbUser);
						}
					}
				} else {
					//就是经办人员
					SysUser sysUser = sysUserService.getById(taskUser.getUnitUserId());
					sysUsers.add(sysUser);
				}
			}
		}
		return sysUsers;
	}


	/**
	 * 保存催办信息
	 *
	 * @param filter
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/saveHasten", method = RequestMethod.POST)
	public Message saveHastenMessage(@RequestBody HastenMessageFilter filter) {
		String s = hastenMessageService.saveHasten(filter);
		if ("200".equals(s)) {
			return coverMessage("200");
		} else {
			return coverMessage("500");
		}
	}

	/**
	 * 督查角色查看催办过的信息
	 *
	 * @return
	 */
	@RequestMapping(value = "/showHasten", method = RequestMethod.GET)
	public String showHasten() {
		return getView("hasten");
	}

	@ResponseBody
	@RequestMapping(value = "/showHasten", method = RequestMethod.POST)
	public JqGrid showHasten(HastenMessageFilter filter) {
		filter.setCreateId(SysUserUtils.getUserId());
		List<HastenMessage> hastenMessageList = hastenMessageService.queryFilter(filter);
		return coverJqGrid(filter, hastenMessageList);
	}

	/**
	 * 根据单位查询用户
	 *
	 * @param deptId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/userList", method = RequestMethod.POST)
	public List<SysUser> userList(String deptId) {
		SysUserFilter filter = new SysUserFilter();
		filter.setDeptId(deptId);
		List<SysLogin> list = sysLoginService.queryUserLoginByRoleDept(filter);
		List<SysUser> userList = new ArrayList<>();
		for (SysLogin sysLogin : list) {
			SysUser user = sysUserService.getById(sysLogin.getSysId());
			userList.add(user);
		}
		return userList;
	}


	/**
	 * 导入承办单位Excel
	 *
	 * @param excelFile
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping(value = "/taskExcel", method = RequestMethod.POST)
	public String taskExcel(@RequestParam MultipartFile excelFile, HttpServletResponse response) throws IOException {
		response.setHeader("Access-Control-Allow-Origin", "*");
		Map<String, Object> map = new HashMap<String, Object>();
		String name = excelFile.getOriginalFilename();
		if (!name.endsWith(".xls") && !name.endsWith(".xlsx")) {
			System.out.println("文件不是excel类型");
			return "文件类型错误";
		} else {
			String s = taskMainService.taskExcel(excelFile.getInputStream(), name);
			if ("200".equals(s)) {
				return "导入Excel成功";
			} else {
				return s;
			}
		}
	}

	/**
	 * 导出督查任务情况一览表
	 *
	 * @param filter
	 * @param response
	 */
	@ResponseBody
	@RequestMapping(value = "/exportTaskMain", method = RequestMethod.GET)
	public void exportTaskMain(@ModelAttribute TaskMainFilter filter, HttpServletResponse response) {
		HSSFWorkbook taskExcel = taskMainService.getTaskExcel(filter);
		HSSFSheet sheet = taskExcel.getSheetAt(0);
		int rowNum = sheet.getLastRowNum();
		if (rowNum == 0) {
			throw new SystemException("没有数据");
		}

		OutputStream out = null;
		try {
			out = response.getOutputStream();

			String filename = "督查任务办理情况表.xls";
			response.setContentType("application/x-msdownload");
			response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
			taskExcel.write(out);
		} catch (Exception e) {

		} finally {
			try {
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}


	/**
	 * 返回修改任务页面
	 *
	 * @param model
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/updateMain/{id}", method = RequestMethod.GET)
	public Map<String, Object> update(Model model, @PathVariable String id) {
		TaskMain taskMain = taskMainService.getById(id);
		TaskMainBean taskMainBean = new TaskMainBean();

		BeanUtils.copyProperties(taskMain, taskMainBean);
		String[] files = splitString(taskMain.getFile());
		String[] fileNames = splitString(taskMain.getFileName());
		List<Map<String, Object>> fileMapList = new ArrayList<>();

		if (ObjectUtils.isNotBlank(files)) {
			for (int i = 0; i < files.length; i++) {
				Map<String, Object> map = new HashMap<>();
				map.put("file", files[i]);
				map.put("fileName", fileNames[i]);
				fileMapList.add(map);
			}
			taskMainBean.setFiles(fileMapList);
		}
		TaskSubFilter taskSubFilter = new TaskSubFilter();
		taskSubFilter.setTaskMainId(id);
		List<TaskCategory> taskCategories = taskCategoryService.query();
		List<TaskSub> taskSubList = taskSubService.queryFilter(taskSubFilter);
		List<TaskSubFilter> subFilterList = new ArrayList<>();
		for (TaskSub taskSub : taskSubList) {
			TaskSubFilter subFilter = new TaskSubFilter();
			BeanUtils.copyProperties(taskSub, subFilter);
			List<TaskUnit> unitList = taskUnitService.getBySubId(taskSub.getSysId());
			subFilter.setTaskUnitList(unitList);
			subFilterList.add(subFilter);
		}
		if (ObjectUtils.isNotBlank(taskMainBean)) {
			Map map = new HashMap<String, Object>();
			map.put("taskMain", taskMainBean);
			map.put("taskCategories", taskCategories);
			return map;
		} else {
			return null;
		}
	}

	/**
	 * 保存修改的主任务
	 *
	 * @param filter
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/updateMain", method = RequestMethod.POST)
	public Message updateTaskMain(@ModelAttribute TaskMainFilter filter) {
		String result = taskMainService.updateTaskMain(filter);
		if ("200".equals(result)) {
			return coverMessage("200");
		} else {
			return coverMessage("500");
		}
	}

	/**
	 * 修改任务删除子任务
	 *
	 * @param subId
	 * @return
	 */
  /*  @ResponseBody
    @RequestMapping(value = "/deleteSub/{subId}", method = RequestMethod.POST)
    public String deleteSub(@PathVariable String subId) {
        String result = taskSubService.deleteSub(subId);
        taskSubService.deleteById(subId);
        if ("200".equals(result)) {
            return "200";
        } else {
            return "500";
        }
    }*/

	/**
	 * 删除单位任务
	 *
	 * @param taskUnitId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/deleteUnit/{taskUnitId}")
	public Message deleteUnit(@PathVariable String taskUnitId) {
		String result = taskMainService.updateDelUnit(taskUnitId);
		if ("200".equals(result)) {
			return coverMessage("200", "删除成功");
		} else {
			return coverMessage("500", "删除失败");
		}
	}

	/**
	 * 返回增加子任务页面
	 *
	 * @param model
	 * @param taskMainId
	 * @return
	 */
	@RequestMapping(value = "/addTaskSub/{taskMainId}")
	public String addTaskSub(Model model, @PathVariable String taskMainId) {
		TaskMain taskMain = taskMainService.getById(taskMainId);
		model.addAttribute("taskMain", taskMain);
		return getView("addTaskSub");
	}


	/**
	 * 保存新增的子任务
	 *
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/addTaskSub", method = RequestMethod.POST)
	public Message addTaskSub(@ModelAttribute TaskSubFilter filter) {
		String result = null;
		try {
			if(StringUtils.isBlank(filter.getUserId()))
			{
				filter.setUserId(SysUserUtils.getUserId());
			}

			//设置 子任务时间类型；
			String timeType = filter.getTimeType();
			String timeLimit = filter.getSubTimeLimit();
			int code = excelDataService.setTimetypeAndLimint(filter, timeType, timeLimit);
			if(code==0)
			{
				return  coverMessage("500","参数错误");
			}


			result = taskMainService.addTaskSub(filter);
		} catch (Exception e) {
			e.printStackTrace();
			return coverMessage("500", e.getMessage());
		}
		if ("200".equals(result)) {
			return coverMessage("200");
		} else {
			return coverMessage("500");
		}
	}

	/**
	 * 返回子事项添加单位页面
	 *
	 * @return
	 */
	@RequestMapping(value = "/addTaskUnit/{taskMainId}")
	public String addTaskUnit(@PathVariable String taskMainId, Model model) {
		TaskMain taskMain = taskMainService.getById(taskMainId);
		//查询当前任务的所有子事项
		List<TaskSub> taskSubs = taskSubService.getByMainId(taskMainId);
		model.addAttribute("taskMain", taskMain);
		model.addAttribute("taskSubs", taskSubs);//当前任务的所有子事项
		return getView("addTaskUnit");
	}

	/**
	 * 排除当前子任务已有单位
	 *
	 * @param taskSubId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/subDeptList/{taskSubId}")
	public List<SysDept> SubDeptList(@PathVariable String taskSubId) {
		List<SysDept> sysDeptList = deptService.queryByDeptLevel(3);
		List<TaskUnit> taskUnits = taskUnitService.getBySubId(taskSubId);
		for (TaskUnit taskUnit : taskUnits) {
			SysDept taskDept = deptService.getById(taskUnit.getDeptId());
			if (StringUtils.isNotBlank(taskDept.getSysId())) {
				//去重
				for (Iterator<SysDept> i = sysDeptList.iterator(); i.hasNext(); ) {
					SysDept o = i.next();
					if (o.getSysId().equals(taskDept.getSysId())) {
						i.remove();
					}
				}
			}
		}
		return sysDeptList;
	}

	/**
	 * 子任务添加单位
	 *
	 * @param filter
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/addTaskUnit", method = RequestMethod.POST)
	public Message addTaskUnit(TaskSubFilter filter) {
		String result = "";
		try {
			result = taskMainService.addTaskUnit(filter);
		} catch (ParseException e) {
			e.printStackTrace();
			return coverMessage("500", "系统错误");
		}
		if ("200".equals(result)) {
			return coverMessage("200", "保存成功");
		} else {
			return coverMessage("500", "保存失败");
		}
	}

	/**
	 * 删除任务（逻辑删除，改变任务状态）
	 *
	 * @param ids 主任务主键
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/delete/{ids}", method = RequestMethod.POST)
	public Message delete(@PathVariable List<String> ids,HttpServletRequest request) {
		String result = taskMainService.updateDel(ids,SysUserUtils.getUserId(),UtilsTools.getClientAddress(request));
		if ("200".equals(result)) {
			return coverMessage("200");
		} else {
			return coverMessage("500");
		}
	}

	/**
	 * 回收站页面
	 *
	 * @return
	 */
	@RequestMapping(value = "/deleteTask")
	public String deleteTask() {
		return getView("deleteTask");
	}

	/**
	 * 删除过的任务(回收站)
	 *
	 * @param filter
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/deleteTask", method = RequestMethod.POST)
	public JqGrid deleteTask(TaskMainFilter filter) {
		String userId = SysUserUtils.getUserId();
		filter.setCreateUser(userId);
		List<TaskMain> taskMainList = taskMainService.queryDelTask(filter);
		return coverJqGrid(filter, taskMainList);
	}

	/**
	 * 删除过的GJ任务(回收站)
	 *
	 * @param filter
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/deleteGJTask", method = RequestMethod.POST)
	public JqGrid deleteGJTask(TaskMainFilter filter) {
		String userId = SysUserUtils.getUserId();
		filter.setCrucialUser(userId);
		List<TaskMain> taskMainList = taskMainService.queryDelTask(filter);
		return coverJqGrid(filter, taskMainList);
	}

	/**
	 * 恢复删除的任务
	 *
	 * @param taskMainId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/recover/{taskMainId}", method = RequestMethod.GET)
	public Message recover(@PathVariable String taskMainId) {
		String result = taskMainService.updateRecover(taskMainId);
		if ("200".equals(result)) {
			return coverMessage("200", "恢复成功");
		} else {
			return coverMessage("500", "恢复失败");
		}
	}


	@Autowired
	private SpecialTaskService specialTaskService;

	/***********************************单位重大立项******************************
	 * 单位重大事项任务类型 督办单位；
	 */
	@RequestMapping(value = "/dubanDeptQuery", method = RequestMethod.GET)
	public  String initDubanDeptQuery(@ModelAttribute SpecialTaskFilter  filter ){


		return getView("dubanQuery");
	}

	@ResponseBody
	@RequestMapping(value = "/dubanDeptQuery", method = RequestMethod.POST)
	public  JqGrid dubanDeptQuery(@ModelAttribute SpecialTaskFilter  filter ){
		String deptId = SysUserUtils.getDeptId();
		//单位督办任务

		TaskMainFilter taskMainFilter = new TaskMainFilter();
		taskMainFilter.setOverdueDept(deptId);
		//去除所有单位重大项目立项数据 返回给前端
		List<TaskMain> newResult =new ArrayList<>();
		List<TaskMain> overdueDeptMain = taskMainService.queryOverdueDept(taskMainFilter);
		for (TaskMain taskMain : overdueDeptMain) {

			filter.setOverdueDeptId(deptId);
			filter.setTaskMainId(taskMain.getSysId());
			List<SpecialTask> specialTasks = specialTaskService.queryFilter(filter);
			if(ObjectUtils.isBlank(specialTasks)){
				continue;
			}
			if(specialTasks.size()>1){
				//BeanUtils.copyProperties(taskMain,);
				for (SpecialTask sptask : specialTasks) {

					TaskMain copytask  = new TaskMain();
					BeanUtils.copyProperties(taskMain,copytask);
					copytask.setTimeLimit(sptask.getRoundLimit());
					copytask.setSpecialTaskId(sptask.getSysId());
					newResult.add(copytask);
				}

			}else {
				TaskMain copytask  = new TaskMain();
				BeanUtils.copyProperties(taskMain,copytask);
				copytask.setSpecialTaskId(specialTasks.get(0).getSysId());
				//copytask.setTimeLimit(sptask.getTimeLimit());
				newResult.add(copytask);
			}

		}


		return coverJqGrid(filter,newResult);
	}

	/**
	 * 二级页面 督办单位反馈给立项单位
	 */
	@RequestMapping(value = "/dubanfeedback/{sysId}", method = RequestMethod.GET)
	public  String Dubanfeedback(@PathVariable String sysId ,Model model){

		System.out.println(sysId);
		SpecialTask specialTasks = specialTaskService.getById(sysId);



		//在获取主任务
		TaskMain mainTask = taskMainService.getById(specialTasks.getTaskMainId());
		//取出特殊任务；这是重大项目类型；
		SpecialTaskFilter specialfilter = new SpecialTaskFilter();
		specialfilter.setTaskMainId(sysId);
		model.addAttribute("mainTask",mainTask);
		model.addAttribute("specialTask",specialTasks);
		SysDept overDue = sysDeptService.getById(specialTasks.getOverdueDeptId());
		model.addAttribute("overdueDept",overDue);
		return getView("duban_feedback_from");
	}

	/**
	 * 督办单位 排名承办单位 upd  20200929
	 * @param sysId
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/dubanfeedback", method = RequestMethod.GET)
	public  String Dubanfeedback(String sysId,String eval,Model model){

		TaskMain mainTask = taskMainService.getById(sysId);

		List<TaskUnit> byMainId = taskUnitService.getByMainId(sysId);
		/*//在获取主任务
		TaskMain mainTask = taskMainService.getById(specialTasks.getTaskMainId());
		//取出特殊任务；这是重大项目类型；
		SpecialTaskFilter specialfilter = new SpecialTaskFilter();
		specialfilter.setTaskMainId(sysId);*/
		model.addAttribute("mainTask",mainTask);
		return getView("duban_feedback_from2");
	}

	/**
	 * 承办单位排名
	 */
	@ResponseBody
	@RequestMapping(value = "/dubanfeedback/getsontask",method = RequestMethod.POST)
	public  Message getSonTasks(@RequestBody TaskUnitFilter filter){
		String sysId = filter.getTaskMainId();
		String timeRound = filter.getTimeRound();


		if(StringUtils.isBlank(sysId)||StringUtils.isBlank(timeRound)){
			return  coverMessage("500","sysId不能为空,或者督办轮次不能为空");
		}
		//返回所有子任务；
		//List<TaskUnit> byMainId = taskUnitService.getByMainId(sysId);

		List<DeptTaskRanksEntity> list = deptTaskRanksService.getRankBymainId(sysId,timeRound);

		if(list.size()==0){
			 list = deptTaskRanksService.saveDeptRank(sysId,timeRound);
		}

//			没有evaluation字段， 前端不会显示排名；
		list.forEach(deptTaskRanksEntity ->
				{
					if (null==deptTaskRanksEntity.getEvaluations()) {
						deptTaskRanksEntity.setEvaluations("-");
					}}

		);
		return coverMessage("200", "承办单位排名", list);
	}

	/**
	 * 更新排名
	 */



	/**
	 * 提交（旧）
	 *
	 */
	@ResponseBody
	@RequestMapping(value = "/submintDbFeedBack", method = RequestMethod.POST)
	public  Message submintDuBanFeedback(@RequestBody TaskMainFilter  filter ){

		if(StringUtils.isBlank(filter.getSysId())){
			return  coverMessage("500","sysId不能为空");
		}
		//List<TaskUnitFilter> taskunitLists = filter.getTaskunitLists();
		int i = ptService.dubanFeedBack(filter);
		if(i>0){
			switch (i){
				case 1:
					return coverMessage("500","请上传附件");
				default:
					return coverMessage("500","操作失败");


			}
		}
		return coverMessage("200","操作成功");
	}

	/**
	 * 督办单位排序承办单位
	 * @param filter
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/rankDepts", method = RequestMethod.POST)
	public  Message rankCBDepts(@RequestBody TaskMainFilter  filter ){

		if(StringUtils.isBlank(filter.getSysId())){
			return  coverMessage("500","sysId不能为空");
		}
		//List<TaskUnitFilter> taskunitLists = filter.getTaskunitLists();
		String sysId = filter.getSysId();
		String json = filter.getJson();

		JSONArray array = JSONArray.parseArray(json);
		List<DeptTaskRanksEntity> list = array.toJavaList(DeptTaskRanksEntity.class);
		list.forEach(deptTaskRanksEntity -> deptTaskRanksEntity.setMainTaskId(sysId));
		//设置评价
		//List<DeptTaskRanksEntity> list1 = deptTaskRanksService.updateDeptRank(list, sysId);
		//更新
		//deptTaskRanksService.batchUpdate(list1);

		return coverMessage("200","操作成功");
	}



	/** 督办反馈
	 * 督办单位任务评价，评价承办单位
	 * 督办单位办结流程
	 * 1 排序承办单位，
	 * 2 上传材料，填写反馈记录,保存到反馈记录表
	 * 3
	 * @param filter
	 * @returnd
	 */
	@ResponseBody
	@RequestMapping(value = "/submitEval", method = RequestMethod.POST)
	public  Message submitEval(@RequestBody  TaskMainFilter  filter ){
		String specialId = filter.getSpecialId();
		if(StringUtils.isBlank(specialId)){
			return  coverMessage("500","督办任务Id不能为空和评价");
		}


		//String json = filter.getJson();
		String loginUserId = SysUserUtils.getUserId();
		if(loginUserId==null){
			loginUserId="20190916100000000883";
		}

		SpecialTask specialTask = specialTaskService.getById(specialId);
		TaskMain taskMain = taskMainService.getById(specialTask.getTaskMainId());
		SysDept deptInfo = deptService.getById(taskMain.getOverdueDept());
		SysDept duchaZu = deptService.getById(taskMain.getInspectionId());

		//当前伦次
		String timeRound = specialTask.getTimeRound();

		//	1 排序承办单位
		//JSONArray array = JSONArray.parseArray(json);
		//List<DeptTaskRanksEntity> list = array.toJavaList(DeptTaskRanksEntity.class);
		List<DeptTaskRanksEntity> list = filter.getListRanks();
		list.forEach(deptTaskRanksEntity -> {deptTaskRanksEntity.setMainTaskId(specialTask.getTaskMainId());deptTaskRanksEntity.setTimeRound(timeRound);});
		//List<DeptTaskRanksEntity> list1 = deptTaskRanksService.updateDeptRank(list, sysId);
		deptTaskRanksService.batchUpdate(list);

		//2保存到反馈记录表
		String mainResult = filter.getMainResult();
		String mainResultFile = filter.getFile();
		String mainResultFileName = filter.getFileName();
		if(StringUtils.isBlank(mainResult)&&StringUtils.isBlank(mainResultFile)&&
		StringUtils.isBlank(filter.getProblem())&&StringUtils.isBlank(filter.getNextPlan()))
		{
			return coverMessage("500","操作失败,您没有反馈任何内容");
		}

		TaskBackNew backEntity = new TaskBackNew();
		backEntity.setFile(mainResultFile);
		backEntity.setFileName(mainResultFileName);
		backEntity.setContent(StringUtils.isBlank(mainResult)?"":mainResult);
		backEntity.setDeptType("3");////反馈类型 1 牵头， 2 协办 ，3 督办单位； 4 攻坚 5 内部
		backEntity.setTaskMainId(taskMain.getSysId());
		backEntity.setTaskUnitId(specialTask.getSysId());
		backEntity.setSenderName(deptInfo.getDeptName());
		backEntity.setRecipientName(duchaZu.getDeptName());
		backEntity.setTimeRound(specialTask.getTimeRound());
		backEntity.setProblem(StringUtils.isBlank(filter.getProblem())?"":filter.getProblem()  );
		backEntity.setPlan(StringUtils.isBlank(filter.getNextPlan())?"":filter.getNextPlan()  );

		//backEntity.setDeptName();
		taskBackNewService.save(backEntity,loginUserId);

		//3 保存到流程记录表 log
		TaskLogNew taskLog = new TaskLogNew();
		taskLog.setTaskSubId(taskMain.getSysId());
		taskLog.setTaskUnitId(specialId);
		taskLog.setContent("督办单位："+deptInfo.getDeptName()+"已反馈给 "+duchaZu.getDeptName()+"");
		taskLogNewService.save(taskLog,loginUserId);


		specialTask.setType("2");//已反馈
		specialTaskService.update(specialTask);






		return coverMessage("200","操作成功");
	}


	/**
	 *  重大事项办理情况 表格数据
	 * @param filter
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getMajorList", method = RequestMethod.POST)
	public JqGrid getMajorList(SpecialTaskFilter filter) {

		//督办单位查看自己的，//督查组查看自己立项的重大立项


		String userId = SysUserUtils.getUserId();
		//filter.setCrucialUser(userId);

		SpecialTaskFilter spFilter = new SpecialTaskFilter();
		//spFilter.setTaskMainId(filter.getTaskMainId());
		List<TaskMajorBean> majorList = specialTaskService.getMajorList(filter);


		return coverJqGrid(filter, majorList);
	}

	/**
	 * 重大事项 三级页面 tab页面
	 */

	@RequestMapping(value = "/duchaDetailView", method = RequestMethod.GET)
	public  String duchaDetailView( String specialId ,String timeRound,Model model,String pagetype){


		if(StringUtils.isBlank(specialId)||StringUtils.isBlank(timeRound)){
			return  "null";

		}
		if(StringUtils.isBlank(pagetype)){
			pagetype="0";
		}
		//System.out.println(sysId);
		SpecialTask specialTasks = specialTaskService.getById(specialId);
		String evaluations = specialTasks.getEvaluations();
		if(StringUtils.isNotBlank(evaluations))
		{
			switch (evaluations){
				case "1":
					specialTasks.setEvaluations("好");
					break;
				case "2":
					specialTasks.setEvaluations("中");
					break;
				case "3":
					specialTasks.setEvaluations("差");
					break;
			}
		}


		//在获取主任务
		TaskMain mainTask = taskMainService.getById(specialTasks.getTaskMainId());

		String[] fileIds = mainTask.getFile().split(",");
		String[] fileNames = mainTask.getFileName().split(",");
		List<AttachmentsDTO> atdtos = new ArrayList<>();
		for (int i = 0; i < fileIds.length; i++) {
			atdtos.add(new AttachmentsDTO(fileIds[i],fileNames[i]));
		}
		mainTask.setFileDTOs(atdtos);

		//取出特殊任务；这是重大项目类型；
		SpecialTaskFilter specialfilter = new SpecialTaskFilter();
		specialfilter.setTaskMainId(specialId);
		model.addAttribute("mainTask",mainTask);
		model.addAttribute("specialTask",specialTasks);
		model.addAttribute("pageType",pagetype);

		SysDept deptInfo = sysDeptService.getById(specialTasks.getOverdueDeptId());
		model.addAttribute("overdueDept",deptInfo);

		SysUser loginUser = sysUserService.getById(SysUserUtils.getUserId());
		if(ObjectUtils.isBlank(loginUser))
		{
			return "/modules/login";
		}
		String personSignal = loginUser.getPersonSignal();
		String loginDeptId = SysUserUtils.getDeptId();
		//判断当前登录是否是督办单位。
		if (specialTasks.getOverdueDeptId().equals(loginDeptId)&&"1".equals(personSignal)) {

			//需要统计本轮已经反馈的和未反馈的子任务；
			TaskBackNewFilter tbnfilter = new TaskBackNewFilter();
			tbnfilter.setDeptType("1");
			tbnfilter.setTimeRound(specialTasks.getTimeRound());
			tbnfilter.setTaskMainId(specialTasks.getTaskMainId());
			List<TaskBackNew> taskBackNews = taskBackNewService.queryAll(tbnfilter);
			List<TaskSub> taskSubList = taskSubService.getByMainId(mainTask.getSysId());
			// 按照子任务id分组；因为 同个子任务有多次反馈记录；
			Map<String, List<TaskBackNew>> subTaskMap = taskBackNews.stream().collect(Collectors.groupingBy(TaskBackNew::getTaskSubId));
			model.addAttribute("feedbacked",taskBackNews.size());
			model.addAttribute("unfeedbacked",(taskSubList.size()-taskBackNews.size()) );
			return  getView("zd_db_feedback");//督办单位的页面
		}

		//督查组页面
		return getView("zd_ducha_feedback");
	}

	/**
	 * 查看单位的历次反馈记录，带参数轮次，查看本轮次的反馈记录
	 */
	@ResponseBody
	@RequestMapping(value = "/historyDuBan", method = RequestMethod.GET)
	public Message getDuBanFeedback(TaskBackNewFilter filter)
	{
		String taskMainId = filter.getTaskMainId();

		List<TaskBackNew> listBacks = taskBackNewService.getListBacks(filter);

		return coverMessage("200", "督办单位反馈记录", listBacks);


	}
	/**
	 * tab1 牵头单位的反馈记录
	 */
	@ResponseBody
	@RequestMapping(value = "/historyQianTou", method = RequestMethod.GET)
	public Message gethistoryQianTou(TaskBackNewFilter filter)
	{
		String taskMainId = filter.getTaskMainId();

		List<HashMap<String, Object>> qianTouBacks = taskBackNewService.getQianTouBacks(filter);

		return coverMessage("200", "督办单位反馈记录", qianTouBacks);


	}

	/**
	 * 办结牵头
	 * 督办单位办结牵头单位反馈
	 * @param filter
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/handleQianTou", method = RequestMethod.POST)
	public Message handleQianTou(@RequestBody TaskBackNewFilter filter)
	{


		String taskUnitId = filter.getTaskUnitId();
		//办结本条单位任务


		//反馈记录设置办结
		String backId = filter.getBackId();
		String status = filter.getStatus();

		if(StringUtils.isBlank(backId)||StringUtils.isBlank(status)||StringUtils.isBlank(taskUnitId))
		{
			return  coverMessage("500","反馈id，单位任务id，办理情况不能为空");
		}
		TaskBackNew taskBack = taskBackNewService.getById(backId);
		taskBack.setStatus(filter.getStatus()); //反馈状态（0未处理，1合格，2重办，3已反馈）
		taskBack.setDubanExplain(filter.getDubanExplain());
		taskBackNewService.update(taskBack);
		if("1".equals(filter.getStatus())){

			TaskUnit taskUnit = taskUnitService.getById(taskUnitId);
			taskUnit.setType("4");//设置为已完成；
		}
		//更新督查流程记录
		TaskLogNew objLog = new TaskLogNew();
		objLog.setContent("督办单位已经办结本轮反馈");
		objLog.setTaskSubId(taskBack.getTaskSubId());
		objLog.setTaskUnitId(taskUnitId);
		taskLogNewService.save(objLog);

		//是否更新 定时任务？？



		return coverMessage("200", "牵头单位反馈办结成功");


	}



	/**
	 * 流程记录
	 */
	@ResponseBody
	@RequestMapping(value = "/liuchengLog", method = RequestMethod.GET)
	public  Message getduchaLog(String taskUnitId){

		List<TaskLogNew> logNewList = taskLogNewService.getByUnitId(taskUnitId);

		return coverMessage("200", "流程记录返回成功", logNewList);

	}



	/**督查组办结
	 * 督查组对 单位重大任务的主任务反馈进行判断 办结重大事项
	 * 督查组对督办单位的评价，
	 * 改评价会直接应用到单位和督办单位；
	 * @param filter
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/handleTask", method = RequestMethod.POST)
	public Message updateMainStatus(@RequestBody TaskMainFilter filter) {
		//督查组的办结是办结 本次 督办单位的所在的督办时限的任务。
		String status = filter.getStatus();
		if(StringUtils.isBlank(status)){
			return coverMessage("500", "办结状态不能为空");
		}
		String specialId = filter.getSpecialId();
		String evaluations = filter.getEvaluations();
		String content = filter.getContent();
		if(StringUtils.isBlank(specialId))
		{
			return coverMessage("500", "评价Id不能为空");
		}

		SpecialTask specialTask = specialTaskService.getById(specialId);
		TaskLogNew logObj = new TaskLogNew();

		if("2".equals(status)){
			specialTask.setType("3+");
			logObj.setContent("督查组已回退本轮事项");
		}else {
			if(StringUtils.isBlank(evaluations)){
				return coverMessage("500", "评价不能为空");
			}
			specialTask.setType(4+"");//已办结；
			specialTask.setEvaluations(evaluations);//设置评价
			//更新评价
			specialTask.setFeedbacks(filter.getMainResult());

			specialTaskService.update(specialTask);

			//更新应用子任务的评价
			String taskMainId = specialTask.getTaskMainId();

			List<DeptTaskRanksEntity> deptRanks = deptTaskRanksService.getRankBymainId(taskMainId,specialTask.getTimeRound());
			if(ObjectUtils.isBlank(deptRanks))//如果承办单位排名空值，就默认排序；
			{
				deptRanks = deptTaskRanksService.saveDeptRank(taskMainId,null);
			}
			deptRanks = deptTaskRanksService.updateDeptRank(deptRanks, evaluations);
			deptTaskRanksService.batchUpdate(deptRanks);
			logObj.setContent("督查组已办结时限为："+specialTask.getRoundLimit()+"的督办事项");
		}

		//更新定时任务；

		// 写入督查路程记录
		logObj.setTaskUnitId(specialTask.getSysId());
		logObj.setTaskSubId(specialTask.getTaskMainId());
		taskLogNewService.save(logObj);

		return coverMessage("200", "处理成功");
	}

	/**
	 * 终止单位重大周期性任务
	 *
	 */

	@ResponseBody
	@RequestMapping(value = "/cancleTask", method = RequestMethod.POST)
	public Message cancleTasks(@RequestBody SpecialTaskFilter filter)
	{
		String taskMainId = filter.getTaskMainId();
		if(StringUtils.isBlank(taskMainId))
		{
			return coverMessage("500","任务取消失败，请联系管理员");
		}

		timeLimitService.updateTask(taskMainId);

		return coverMessage("200","成功终止了任务！");



	}

	/**
	 * 情况导入缓存批次号
	 * @param type
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/delredis", method = RequestMethod.GET)
	public Message delRedis(String type)
	{
		String loginUserId = SysUserUtils.getUserId();
		if("1".equals(type)){

			redisService.del("batchNum:"+loginUserId);
		}
		if("2".equals(type))
		{
			redisService.del("insideBatch:"+loginUserId);

		}

		return coverMessage("200","清空缓存成功");



	}

	/**
	 * 重大事项统计
	 */
	@ResponseBody
	@RequestMapping(value = "/getdeptRanks", method = RequestMethod.GET)
	public Message getDeptRanks (String taskMainId){

		if(StringUtils.isBlank(taskMainId))
		{
			return  coverMessage("500","参数不能为空");
		}

		HashMap<String, Object> taskDeptRanks = deptTaskRanksService.getTaskDeptRanks(taskMainId);

		return coverMessage("200","22",taskDeptRanks);
	}





	/**
	 * add 2021-03-22
	 * 攻坚角色任务新页面 转立项页面二级页面
	 */
	@RequestMapping(value = "/showgjview/{id}", method = RequestMethod.GET)
	public  String showGongjianView(Model model,@PathVariable String id )
	{

		model.addAttribute("taskMainId", id);
		TaskMain taskMain = taskMainService.getById(id);
		TaskMainBean taskMainBean = new TaskMainBean();
		BeanUtils.copyProperties(taskMain, taskMainBean);
		String[] files = splitString(taskMain.getFile());
		String[] fileNames = splitString(taskMain.getFileName());
		String[] gJFiles = splitString(taskMain.getgJFile());
		String[] gJfileName = splitString(taskMain.getgJFileName());
		String[] resultFiles = splitString(taskMain.getMainResultFile());
		String[] resultFileNames = splitString(taskMain.getMainResultFileName());
		List<Map<String, Object>> fileMapList = new ArrayList<>();
		if (ObjectUtils.isNotBlank(files)) {
			for (int i = 0; i < files.length; i++) {
				Map<String, Object> map = new HashMap<>();
				map.put("file", files[i]);
				map.put("fileName", fileNames[i]);
				fileMapList.add(map);
			}
			taskMainBean.setFiles(fileMapList);
		}
		if (ObjectUtils.isNotBlank(gJFiles)) {
			List<Map<String, Object>> gjFileMapList = new ArrayList<>();
			for (int i = 0; i < gJFiles.length; i++) {
				Map<String, Object> map = new HashMap<>();
				map.put("file", gJFiles[i]);
				map.put("fileName", gJfileName[i]);
				gjFileMapList.add(map);
			}
			taskMainBean.setgJFile(gjFileMapList);
		}
		if (ObjectUtils.isNotBlank(resultFiles)) {
			List<Map<String, Object>> resultFileMapList = new ArrayList<>();
			for (int i = 0; i < resultFiles.length; i++) {
				Map<String, Object> map = new HashMap<>();
				map.put("file", resultFiles[i]);
				map.put("fileName", resultFileNames[i]);
				resultFileMapList.add(map);
			}
			taskMainBean.setMainResultFile(resultFileMapList);
		}

		model.addAttribute("taskMain", taskMainBean);
		String roleId = SysUserUtils.getRoleId();
		SysDept dept = deptService.getById(SysUserUtils.getDeptId());
		model.addAttribute("roleId", roleId);

		// imp 1 =重大事项，，2 攻坚事项
		if(taskMain.getImp()==2){

		}

		if ("20190722100000000194".equals(dept.getSysId())) {
			//如果是攻坚作战室单位，当查看该任务后，该任务就不是在办
			taskMain.setCrucialState(null);
			taskMainService.update(taskMain);
		}
		model.addAttribute("dept", dept);

		return  getView("gongjian_task_showItemList");
	}

	/**
	 *站立项任务-页面二级页面
	 * @param filter
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/showgjview/",method = RequestMethod.POST)
	public JqGrid getDuChaProjects(SpecialTaskFilter filter)
	{
		String taskMainId = filter.getTaskMainId();

		List<TaskMajorBean> spcialTaskList = specialTaskService.getMajorList(filter);
		for (TaskMajorBean item : spcialTaskList) {
			String s = redisService.get("dept:" + item.getDeptId());
			try {
				SysDept sysDept = JSONObject.parseObject(s, SysDept.class);
				item.setDeptName(sysDept.getDeptName());
			}catch (Exception e){
				item.setDeptName("未知错误");
			}
		}


		return coverJqGrid(filter,spcialTaskList);

	}




	/** add  2021-03-23
	 * 督查组反馈给作战室的详情页
	 */
	@RequestMapping(value = "/duchaDetailView/{id}",method = RequestMethod.GET)
	public String showDuChaDetailView(Model model,@PathVariable String id)
	{
		//子任务的Id
		SpecialTask specialTask = specialTaskService.getById(id);
		String mainId = specialTask.getTaskMainId();
		TaskMain taskMain = taskMainService.getById(mainId);


		TaskMainBean taskMainBean = new TaskMainBean();
		BeanUtils.copyProperties(taskMain, taskMainBean);
		String[] files1 = splitString(taskMain.getFile());
		String[] fileNames1 = splitString(taskMain.getFileName());
		String[] gJFiles = splitString(taskMain.getgJFile());
		String[] gJfileName = splitString(taskMain.getgJFileName());
		String[] resultFiles = splitString(taskMain.getMainResultFile());
		String[] resultFileNames = splitString(taskMain.getMainResultFileName());
		List<Map<String, Object>> fileMapList1 = new ArrayList<>();
		if (ObjectUtils.isNotBlank(files1)) {
			for (int i = 0; i < files1.length; i++) {
				Map<String, Object> map = new HashMap<>();
				map.put("file", files1[i]);
				map.put("fileName", fileNames1[i]);
				fileMapList1.add(map);
			}
			taskMainBean.setFiles(fileMapList1);
		}
		if (ObjectUtils.isNotBlank(gJFiles)) {
			List<Map<String, Object>> gjFileMapList = new ArrayList<>();
			for (int i = 0; i < gJFiles.length; i++) {
				Map<String, Object> map = new HashMap<>();
				map.put("file", gJFiles[i]);
				map.put("fileName", gJfileName[i]);
				gjFileMapList.add(map);
			}
			taskMainBean.setgJFile(gjFileMapList);
		}
		if (ObjectUtils.isNotBlank(resultFiles)) {
			List<Map<String, Object>> resultFileMapList = new ArrayList<>();
			for (int i = 0; i < resultFiles.length; i++) {
				Map<String, Object> map = new HashMap<>();
				map.put("file", resultFiles[i]);
				map.put("fileName", resultFileNames[i]);
				resultFileMapList.add(map);
			}
			taskMainBean.setMainResultFile(resultFileMapList);
		}
		model.addAttribute("taskMain", taskMainBean);
		return  getView("gongjian_details");

	}


	/**
	 *
	 * 获取子任务下的所有单位任务
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/gettaskunit", method = RequestMethod.GET)
	public List<TaskUnit> getTaskUnits(String  taskUnitId)
	{
		if(taskUnitId==null){
			return new ArrayList<TaskUnit>();
		}
//		taskMainId="20210506100000000829";
		TaskUnit taskUnit = taskUnitService.getById(taskUnitId);

		String timeRound = taskUnit.getTimeRound();
		List<TaskUnit> taskUnitList = taskUnitService.getBySubId2(taskUnit.getTaskSubId());
		List<TaskUnit> collect = taskUnitList.stream().filter(taskUnit1 -> taskUnit1.getTimeRound().equals(timeRound)).collect(Collectors.toList());

		/*TaskUnitFilter filter = new TaskUnitFilter();
		Paging paging = new Paging();
		filter.setPaging(paging);*/
		return collect;

	}

	/**
	 * 终止单个任务
	 * @param taskUnitId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/stopUnit/{taskUnitId}", method = RequestMethod.POST)
	public Message  stopunit(@PathVariable String taskUnitId)
	{
		System.out.println(taskUnitId);
		TaskUnit taskunit = taskUnitService.getById(taskUnitId);
		if(ObjectUtils.isNotBlank(taskunit))
		{
			//0 需要继续循环 1 不要循环
			int cycflag = taskunit.getCycflag();
			if(1==cycflag)
			{
				return coverMessage("200","已经终止该任务");
			}else {
				taskunit.setCycflag(1);
				taskUnitService.update(taskunit);
				return coverMessage("200","任务终止成功");
			}
		}

		return coverMessage("500","操作失败，联系管理员");
	}

	/**
	 * 终止冰办结单个任务
	 * @param taskUnitId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/stopUnitAndEnd/{taskUnitId}", method = RequestMethod.POST)
	public Message  stopandEndUnit(@PathVariable String taskUnitId)
	{
		System.out.println(taskUnitId);
		TaskUnit taskunit = taskUnitService.getById(taskUnitId);
		if(ObjectUtils.isNotBlank(taskunit))
		{
			//0 需要继续循环 1 不要循环
			int cycflag = taskunit.getCycflag();
			if(1==cycflag)
			{
				return coverMessage("200","已经终止该任务");
			}else {
				taskunit.setCycflag(1);
				taskunit.setType(4+"");
				taskUnitService.update(taskunit);
				return coverMessage("200","任务终止成功");
			}
		}

		return coverMessage("500","操作失败，联系管理员");
	}

	/**
	 * 终止任务
	 * @param taskMainId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/stopTask/{taskMainId}", method = RequestMethod.GET)
	public Message  stopAllTask(@PathVariable String taskMainId)
	{
		System.out.println(taskMainId);
//		TaskUnit taskunit = taskUnitService.getById(taskUnitId);
		TaskMain taskMain = taskMainService.getById(taskMainId);
		if(ObjectUtils.isNotBlank(taskMain))
		{
			taskMainService.updateStopAllTask(taskMainId);
			return coverMessage("200","任务已经终止，不再生成下一轮");

		}


		return coverMessage("500","操作失败，找不到任务,联系管理员");
	}


}
